WebArticle12 min read

Building a dating app without an ORM

Matcha: matching ranked in hand-written SQL, revocable sessions in HttpOnly cookies, live chat and peer-to-peer audio calls. Explained with the real code, plus the discovery query to run yourself.

By Abdeljalil El HidaouiSource code
On this page

A dating app looks simple from the outside: profiles, a like button, a chat. Underneath, it has to decide who should see whom, keep conversations live across tabs, connect two browsers for a voice call, and make sure a stolen cookie or a blocked user can't get anywhere.

Matcha is the 42 web project we built in a team of two: a complete dating site with profiles, ranked suggestions, a map, matches, real-time chat, audio calls and date planning. This article focuses on the parts that were the most interesting to get right, with the real code from the repository, and lets you run the matching query yourself.

The stack

The front end is Next.js with React and TypeScript. The back end is Flask with Flask-SocketIO for real-time events, on PostgreSQL. One rule of the subject shaped everything: no ORM. Every query is hand-written SQL, sent through psycopg2 with a connection pool. The whole stack starts with Docker Compose and one script, which also seeds 500 realistic profiles to browse.

API routes
50+
PostgreSQL tables
14
ORM: all SQL by hand
0
seeded profiles
500
Next.js front end, Flask REST API and Socket.IO, PostgreSQL, and external services
The Next.js front end calls the Flask REST API for actions and listens to Flask-SocketIO for live events; both share one PostgreSQL database.Open full size

The data model

Without an ORM, the schema is where the rules live. Fourteen tables hang off users, all deleted with it. The likes table shows the style: the pair of user ids is the primary key, so the same like can never be stored twice, and a check stops anyone liking themselves.

backend/schema.sqlView on GitHub
CREATE TABLE IF NOT EXISTS user_likes (
    liker_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    liked_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    created_at TIMESTAMP NOT NULL DEFAULT now(),
    PRIMARY KEY (liker_id, liked_id),
    CHECK (liker_id <> liked_id)
);

A match isn't stored anywhere: it is simply a like in both directions. And a partial unique index guarantees that each user has exactly one profile picture, enforced by the database itself rather than by application code that could forget:

backend/schema.sqlView on GitHub
CREATE UNIQUE INDEX IF NOT EXISTS idx_photos_one_primary_per_user
    ON photos(user_id)
    WHERE is_primary = TRUE;
The fourteen tables of Matcha and their relations
Fourteen tables, all attached to users with ON DELETE CASCADE. Pair tables use both user ids as their primary key.Open full size

Who should you see?

The suggestions page is one SQL query, built in two steps. First, it keeps only the people who could be a match: complete, verified profiles whose gender fits your preferences, while your gender fits theirs, and with no block in either direction.

backend/app/models.pyView on GitHub
WHERE u.id <> current_profile.id
  AND u.is_verified = true
  AND u.birth_date IS NOT NULL
  AND u.gender IS NOT NULL
  AND CARDINALITY(u.sexual_preferences) BETWEEN 1 AND 3
  AND LENGTH(BTRIM(COALESCE(u.biography, ''))) > 0
  AND LENGTH(BTRIM(COALESCE(u.location_name, ''))) > 0
  AND u.latitude IS NOT NULL
  AND u.longitude IS NOT NULL
  AND u.gender = ANY(current_profile.sexual_preferences)
  AND current_profile.gender = ANY(u.sexual_preferences)
  AND EXISTS (
      SELECT 1
      FROM user_tags required_tag
      WHERE required_tag.user_id = u.id
  )
  AND NOT EXISTS (
      SELECT 1
      FROM user_blocks blocked
      WHERE (
          blocked.blocker_id = current_profile.id
          AND blocked.blocked_id = u.id
      ) OR (
          blocked.blocker_id = u.id
          AND blocked.blocked_id = current_profile.id
      )
  )

Then it measures each candidate. Distance is computed in SQL with the Haversine formula, which gives the distance between two points on a sphere from their latitudes and longitudes:

backend/app/models.pyView on GitHub
6371.0 * 2 * ASIN(
    SQRT(
        LEAST(
            1.0,
            GREATEST(
                0.0,
                POWER(
                    SIN(
                        RADIANS(
                            u.latitude - current_profile.latitude
                        ) / 2
                    ),
                    2
                )
                + COS(RADIANS(current_profile.latitude))
                * COS(RADIANS(u.latitude))
                * POWER(
                    SIN(
                        RADIANS(
                            u.longitude - current_profile.longitude
                        ) / 2
                    ),
                    2
                )
            )
        )
    )
) AS distance_km

The LEAST and GREATEST around it are a small numerical safety net: rounding can push the value just past 1, and ASIN of 1.0000001 is an error. The query also decides whether you live in the same area by comparing the city part of the two location names:

backend/app/models.pyView on GitHub
(
    LOWER(BTRIM(
        CASE
            WHEN POSITION(',' IN u.location_name) > 0
            THEN SPLIT_PART(u.location_name, ',', 2)
            ELSE u.location_name
        END
    )) = LOWER(BTRIM(
        CASE
            WHEN POSITION(',' IN current_profile.location_name) > 0
            THEN SPLIT_PART(current_profile.location_name, ',', 2)
            ELSE current_profile.location_name
        END
    ))
) AS same_area,

Finally, the ranking. “Recommended” is not a weighted score but a strict order of priorities: same area first, then the nearest, then the most shared interests, then the most popular.

backend/app/models.pyView on GitHub
def discover_users(current_user_id, filters):
    """Execute the compatibility, privacy, filter, ranking, and pagination SQL."""
    order_by = {
        'recommended': (
            'same_area DESC, distance_km ASC, '
            'common_tag_count DESC, fame_rating DESC, id ASC'
        ),
        'age': f"age {filters['order'].upper()}, id ASC",
        'distance': f"distance_km {filters['order'].upper()}, id ASC",
        'fame': f"fame_rating {filters['order'].upper()}, id ASC",
        'commonTags': (
            f"common_tag_count {filters['order'].upper()}, id ASC"
        ),
    }[filters['sort']]

Here is that query, run in your browser on a few sample profiles. Change who you are, where you live and what you like:

Run the discovery query

The same filters and ORDER BY as the SQL. Try changing your preferences, your city or the sort, or block someone.

You

Your gender

Looking for

Your interests

Filters

6 suggestion(s)

  1. 1LLina, 24 Casablancasame area0.0 km0 sharedfame 41
  2. 2SSara, 26 Casablancasame area4.3 km2 shared (#travel #coffee)fame 64
  3. 3YYasmine, 29 Rabat85 km1 shared (#coding)fame 82
  4. 4IImane, 27 Benguerir153 km3 shared (#coding #coffee #travel)fame 55
  5. 5HHiba, 35 Marrakech220 km1 shared (#travel)fame 38
  6. 6SSalma, 22 Tangier296 km1 shared (#coffee)fame 27

3 filtered out

  • Nora · they are not looking for: man
  • Alex · you are not looking for: non-binary
  • Adam · you are not looking for: man

Sample profiles invented for this demo; the real app ranks 500 seeded accounts the same way. Distances use real city coordinates.

The discovery query: filters first, then the ranking keys
Filter, then rank: same city first, then the nearest, then shared interests, then fame.Open full size

A fame rating

The subject asks for a public “fame rating”. Ours is deliberately simple and explainable: likes count the most, profile views a little, and a complete profile earns up to 10 points. The result is kept between 0 and 100.

backend/app/models.pyView on GitHub
def calculate_fame_rating(user_id):
    """Calculate the documented, bounded fame score from likes, views, and completion."""
    likes = query_one(
        "SELECT COUNT(*) AS c FROM user_likes WHERE liked_id = %s",
        (user_id,),
    )['c']
    views = query_one(
        "SELECT COUNT(*) AS c FROM user_views WHERE viewed_id = %s",
        (user_id,),
    )['c']

    user = get_user_by_id(user_id)
    tags = get_tags_for_user(user_id)
    photos_count = count_photos(user_id)
    completion = profile_completion_points(user, tags, photos_count)

    raw_rating = (likes * 3) + (views * 0.5) + completion
    return min(MAX_FAME_RATING, max(0, round(raw_rating, 2)))
backend/app/models.pyView on GitHub
def profile_completion_points(user, tags, photos_count):
    """Calculate the documented profile-completion component of fame rating."""
    points = 0
    if user['birth_date']:
        points += 1
    if user['gender']:
        points += 1
    if user['sexual_preferences']:
        points += 1
    if user['biography']:
        points += 2
    if tags:
        points += 1
    if photos_count > 0:
        points += 2
    if user['latitude'] is not None and user['longitude'] is not None:
        points += 2
    return points
Compute a fame rating

Profile completion 8 / 10

8×3 + 40×0.5 + 8 = 52

52 / 100

The score is recomputed after every like and every profile visit.

From a like to a match

Liking someone inserts one row. If the other person already liked you, that single action becomes a match: both users get a notification, and a live event unlocks the conversation on both sides at once.

backend/app/users.pyView on GitHub
if not models.like_user(current_user['id'], target['id']):
    return jsonify({'message': 'You already liked this user'}), 409

mutual = models.has_liked(target['id'], current_user['id'])
if mutual:
    models.create_notification(target['id'], 'match', from_user_id=current_user['id'])
    models.create_notification(current_user['id'], 'match', from_user_id=target['id'])
    emit_conversation_status(
        current_user['id'],
        target['id'],
        True,
        'match',
        current_user['id'],
    )
else:
    models.create_notification(target['id'], 'like', from_user_id=current_user['id'])

models.update_fame_rating(target['id'])

return jsonify({'liked': True, 'isConnected': mutual}), 200

Thanks to the primary key, liking the same person twice can't create a duplicate: the insert uses ON CONFLICT DO NOTHING, and the API answers 409 instead.

Sessions you can revoke

Login uses JWTs, but stored in HttpOnly cookies, so JavaScript running on the page, including any injected script, can never read them. Cookies are sent automatically by the browser, which opens the door to cross-site request forgery, so CSRF protection is switched on: every state-changing request must also carry a token in a header, which another site cannot read or set.

backend/app/config.pyView on GitHub
JWT_ACCESS_TOKEN_EXPIRES = timedelta(minutes=180)
JWT_REFRESH_TOKEN_EXPIRES = timedelta(days=7)
JWT_TOKEN_LOCATION = ['cookies'] # Store JWTs in cookies instead of headers.
JWT_COOKIE_SECURE = False # for local development, True in production
JWT_COOKIE_SAMESITE = 'Lax' # for local development, Strict in production
JWT_COOKIE_CSRF_PROTECT = True # Enable CSRF protection for JWT cookies. (CSRF protection is important for cookies to prevent cross-site request forgery attacks)
JWT_CSRF_IN_COOKIES = True
JWT_ACCESS_COOKIE_PATH = '/'
JWT_REFRESH_COOKIE_PATH = '/api/auth/refresh'
JWT_ACCESS_CSRF_COOKIE_PATH = '/'
JWT_REFRESH_CSRF_COOKIE_PATH = '/'

Plain JWTs have one weakness: once issued, they are valid until they expire. To be able to log someone out for real, every token carries a session id and a version number, and every request checks them against the database:

backend/app/extensions.pyView on GitHub
@jwt.token_in_blocklist_loader
def token_is_revoked(jwt_header, jwt_payload):
    from app import models

    try:
        user_id = int(jwt_payload.get('sub'))
    except (TypeError, ValueError):
        return True

    return not models.is_session_active(
        jwt_payload.get('sid'),
        user_id,
        jwt_payload.get('ver'),
    )
backend/app/models.pyView on GitHub
def is_session_active(session_id, user_id, token_version):
    if not session_id or user_id is None or token_version is None:
        return False

    return query_one(
        """
        SELECT 1
        FROM auth_sessions s
        JOIN users u ON u.id = s.user_id
        WHERE s.id = %s
          AND s.user_id = %s
          AND s.revoked_at IS NULL
          AND s.expires_at > now()
          AND u.token_version = %s
        """,
        (session_id, user_id, token_version),
    ) is not None

Logging out revokes one session. Resetting a password goes further: it bumps the user's token version, which instantly invalidates every token on every device, and closes their open sockets too.

backend/app/auth.pyView on GitHub
models.reset_password_and_revoke_sessions(
    user['id'],
    new_password,
    user['token_version'] + 1,
)

from app.sockets import disconnect_user
disconnect_user(user['id'])

response = jsonify({'message': 'Password reset successfully'})
unset_jwt_cookies(response)
return response, 200
Login, cookies, CSRF and session checks
Each protected request is checked four ways: signature, CSRF header, live session and token version.Open full size

Chat, presence and calls

Chat messages, notifications and online status travel over Socket.IO. The socket handshake carries the same HttpOnly cookie, so a connection is accepted only for a live session. Each user then joins a private room named after their id, which means a message reaches every tab they have open:

backend/app/sockets.pyView on GitHub
@socketio.on('connect')
def handle_connect(auth):
    """
    The browser sends the HttpOnly access-token cookie during the Socket.IO
    handshake. A connection is accepted only while the server-side session
    row is active.
    """
    authenticated_session = _authenticated_socket_session()
    if authenticated_session is None:
        disconnect()
        return False

    user_id, session_id = authenticated_session
    join_room(f'user:{user_id}')

    sid = request.sid
    with _lock:
        is_first_connection = len(_user_connections[user_id]) == 0
        _user_connections[user_id].add(sid)
        _session_connections[session_id].add(sid)
        _sid_to_user[sid] = user_id
        _sid_to_session[sid] = session_id

    if is_first_connection:
        from app import models
        models.set_user_online(user_id, True)
        socketio.emit('presence', {'userId': user_id, 'isOnline': True, 'lastActivity': None})

Audio calls use WebRTC, where the sound goes directly from one browser to the other. But two browsers can't find each other on their own: they first exchange an offer, an answer and network candidates. Our server relays those messages, and nothing more. Before each one, it checks that the two people are still matched and haven't blocked each other, and it validates the size and shape of the payload:

backend/app/sockets.pyView on GitHub
@socketio.on('call_signal')
def handle_call_signal(data):
    """Relay validated WebRTC signaling only between call participants."""
    user_id = _socket_user_id()
    if user_id is None or not isinstance(data, dict):
        return {'ok': False, 'message': 'Unauthorized'}

    call_id = _call_id_from_data(data)
    signal_type = data.get('type')
    signal = data.get('signal')
    if call_id is None:
        return {'ok': False, 'message': 'Invalid call request'}
    if not _valid_call_signal(signal_type, signal):
        return {'ok': False, 'message': 'Invalid call signal'}

    with _call_lock:
        call = _calls.get(call_id)
        if not call or call['status'] != 'active':
            return {'ok': False, 'message': 'Call is not active'}
        other_user_id = _other_call_user(call, user_id)
        if other_user_id is None:
            return {'ok': False, 'message': 'Unauthorized'}

    if not _call_relationship_allowed(user_id, other_user_id):
        end_calls_between(user_id, other_user_id, 'connection_lost')
        return {'ok': False, 'message': 'Connection is no longer active'}

    socketio.emit(
        'call_signal',
        {
            'callId': call_id,
            'type': signal_type,
            'signal': signal,
        },
        room=f'user:{other_user_id}',
    )
    return {'ok': True}
backend/app/sockets.pyView on GitHub
def _call_relationship_allowed(user_a_id, user_b_id):
    """Verify both profiles remain complete, connected, and non-blocked."""
    from app import models

    if user_a_id == user_b_id:
        return False
    if not models.get_user_by_id(user_b_id):
        return False
    if not models.is_user_profile_complete(user_b_id):
        return False
    if models.is_blocked_either_way(user_a_id, user_b_id):
        return False
    return models.is_connected(user_a_id, user_b_id)
Socket.IO rooms per user and the WebRTC signaling relay
Socket.IO delivers chat and notifications to every tab; for calls, the server only relays the WebRTC setup and the audio goes peer to peer.Open full size

Small things that matter

Security in a project like this is mostly a long list of small, boring decisions. A few of them:

  • Passwords are hashed with bcrypt, checked for strength, and refused if they are based on the user's own name, username or email.
  • Every query is parameterised; the only dynamic SQL comes from allow-listed values.
  • Blocks apply everywhere: search, profiles, chat and calls.
  • Map positions are rounded before being sent, so nobody's exact location is exposed.
  • Every response carries defensive headers:
backend/app/__init__.pyView on GitHub
@app.after_request
def add_security_headers(response):
    response.headers.setdefault('X-Content-Type-Options', 'nosniff') # prevents the browser from interpreting files and scripts as a different MIME type.
    response.headers.setdefault('X-Frame-Options', 'DENY') # prevents clickjacking attacks by preventing the page from being displayed in a frame or iframe
    response.headers.setdefault('Referrer-Policy', 'strict-origin-when-cross-origin') # controls how much referrer information is sent with requests, helping to protect user privacy
    response.headers.setdefault('Permissions-Policy', 'camera=(), microphone=(self), geolocation=(self)')
    response.headers.setdefault('Cross-Origin-Resource-Policy', 'same-site') # prevents the browser from loading resources from other origins``.
    if request.path.startswith('/api/'):
        response.headers.setdefault('Cache-Control', 'no-store')
    return response

What I learned

  • Writing SQL by hand teaches you the database. Without an ORM, constraints, indexes and a single well-built query do work that would otherwise be scattered across the code.
  • Real time multiplies the edge cases. Several tabs, a dropped connection, a block during a call: each one needed explicit handling on the server.
  • “Logged out” should mean logged out. Revocable sessions cost one query per request and are worth it.
  • Secrets never belong in Git. Configuration should come from the environment, with an example file committed instead of the real one.

The full code, with a detailed README covering the API, the socket events and the schema, is on GitHub.

About the project: Matcha

A complete dating web app built in a team of two: profiles with photos and location, ranked suggestions and a map, likes that turn into matches, then live chat, audio calls and date planning. Flask on raw SQL behind a Next.js frontend, started with one script.

  • Raw SQL, no ORM
  • WebRTC calls
  • 500 seeded profiles

Built with

  • Next.js
  • React
  • TypeScript
  • Tailwind CSS
  • Flask
  • Flask-SocketIO
  • PostgreSQL
  • psycopg2
  • WebRTC
  • JWT
  • OAuth 2.0
  • Docker Compose