The Problem#
A swipe-based dating app such as Tinder, Bumble or Hinge shows each user a stack of nearby profiles that fit their preferences. The user swipes right ("yes", a like) or left ("no", a pass) on each profile, one at a time. When two people have both swiped right on each other, it is a match, and both are told, so they can start chatting.
The product looks trivial: a list of photos and two buttons. The engineering is not:
- The stack must load instantly. It must contain only people within the user's distance limit, inside their age range, and of the gender they are interested in. Ideally the user also fits those people's preferences. And it must never show someone the user has already swiped on.
- Swiping is effortless, so writes are huge. Tens of millions of users swiping a hundred times a day produce billions of writes per day, far more than profile edits or reads.
- Matches must never be lost. If two people swipe right on each other at nearly the same instant, a naive "check then write" can miss the match on both sides. Each user then believes the other never liked them.
- History grows without bound. A long-time user may have swiped on tens of thousands of people. Excluding all of them from every new stack, cheaply, is its own problem.
Analogy. Imagine a matchmaker at a large party. Before you arrive, they prepare a stack of cards for you, each describing someone nearby who fits what you said you want. That is the precomputed recommendation stack. They hand you the cards one by one. You put each card in a "yes" or "no" tray, and they record your decision in a giant ledger. That is the swipe write path. Whenever you put someone in "yes", the matchmaker checks whether that person has already put you in their "yes" tray. If so, they ring a bell for both of you, the match. The matchmaker must never hand you a card for someone you have already sorted. For a regular with thousands of past decisions, re-reading the whole ledger each time is slow, so they keep a small cheat sheet that can say "definitely not seen before" instantly and is only occasionally over-cautious. That is the Bloom filter. And if two people drop each other's cards in the "yes" tray at exactly the same moment, the matchmaker needs a rule that guarantees the bell still rings. That is consistent match detection.
This problem tests whether a candidate can:
- design a low-latency, filtered, geo-aware feed with precomputation;
- handle write-heavy data with the right database and partitioning;
- reason precisely about consistency under concurrency (the mutual-swipe race);
- apply a probabilistic data structure correctly, including what its false positives mean for the product.
Clarifying Questions#
| Question | Why it matters | Assumed answer |
|---|---|---|
| Which features are core? | Scope. | Profile with preferences and max distance, the recommendation stack, swiping, and match notifications. |
| Are photos, chat and premium features in scope? | They are big systems of their own. | Below the line. Photos are standard blob storage plus CDN; chat is its own design (see the chat-system problem); premium features are mentioned only where they affect the design. |
| How many users? | Sizing. | 20 million daily active users, about 100 swipes per user per day on average, with heavy users at several hundred. |
| How strict must match detection be? | Consistency model. | Strongly consistent: if B swipes yes on A, who already swiped yes on B, B must see the match immediately and A must be notified. |
| Latency target for loading the stack? | Feed architecture. | Under 300 ms to show the first profiles. |
| Can a profile reappear after a swipe? | History filtering. | No. Users should not be shown people they have already swiped on. |
| How is location handled? | Geo design. | The client sends its current location; the stack includes only people within the user's chosen maximum distance (for example 2, 5 or 15 miles). |
| Do we need two-way preference matching? | Feed quality. | Yes, ideally: show B to A only if B fits A's filters and A fits B's filters. |
| Safety and fake profiles? | Abuse. | Below the line, but we mention blocks, reports and rate limits where they touch the design. |
Requirements#
Functional requirements#
- Create a profile with preferences: age range, gender(s) of interest, interests and a maximum distance.
- View a stack of potential matches: profiles that satisfy the user's preferences and lie within their maximum distance of their current location.
- Swipe: right ("yes") or left ("no") on profiles, one at a time.
- Match notification: both users learn of a match when they have swiped yes on each other. The second swiper sees it instantly, and the first gets a push notification.
Below the line: photo upload, chat after a match, "super likes" and other premium features, fake-profile protection, and monitoring and alerting (we still sketch monitoring later).
Non-functional requirements#
- Strong consistency for swiping: a mutual yes must always produce a match, even when both swipes arrive at the same instant.
- Scale: 20 million DAU × about 100 swipes per day, which is about 2 billion swipes per day.
- Low latency: the stack loads in under 300 ms. Swipes are acknowledged in tens of milliseconds, so the card animation never waits.
- No repeats: never show a profile the user has already swiped on.
- Availability: the app should keep working (stacks load, swipes are accepted) through partial failures. Consistency is needed specifically for match detection.
The framing to say out loud: this is a geo-filtered recommendation feed on the read side and a write-heavy, concurrency-sensitive event log on the swipe side. I will precompute stacks so reads are fast, keep swipes in a write-optimised store partitioned for the access patterns I need, make match detection atomic per pair, and use the client plus a Bloom filter to stop repeats.
Capacity Estimation#
Quick numbers, using Back-of-the-Envelope Estimation.
Users.
- 20 million daily active users. Assume around 75 million monthly actives and around 100 million swipeable profiles in total, active or dormant.
Swipes (writes).
- 20M × 100 swipes per day = 2 billion swipes per day. Some estimates use 200 swipes per user, giving 4 billion; the design must cope with either.
- 2 × 10^9 / 86,400 ≈ 23,000 swipes per second on average. Evenings are busy, so take a peak factor of 3: about 70,000 per second, and up to 140,000 per second if we assume 200 swipes per user.
- Each swipe record (swiper ID, target ID, decision, timestamp, plus storage overhead) is about 100 bytes. That gives 2 × 10^9 × 100 B = 200 GB per day of new swipe data, about 73 TB per year before replication, or about 220 TB per year with a replication factor of 3.
- Assume about a third of swipes are likes: about 670 million likes per day.
Matches.
- If around 1 to 2 percent of likes are reciprocated, that is roughly 7 to 13 million matches per day, about 100 to 150 per second, each producing one push notification.
- These figures are for sizing only. Real match rates vary widely between products and user groups.
Stack (reads).
- Assume users open the app about 5 times a day and each session consumes one stack of up to 200 profiles: 20M × 5 = 100 million stack requests per day, about 1,200 per second on average and around 4,000 per second at peak.
- Reads are therefore far rarer than writes in requests per second. But each read is expensive, because it is a filtered, geo-bounded, history-excluding search.
- The latency budget is 300 ms. A precomputed stack read from a cache takes about 1 to 5 ms; a real-time search takes 50 to 200 ms.
Profiles and the search index.
- 100 million profiles × about 1 KB of searchable fields (age, gender, preferences, location, a few interest tags, activity timestamps) = 100 GB in the search index. Photos and long bios live elsewhere.
- Location updates: about 5 per user per day on app open, so 100 million per day, about 1,200 per second. Each updates one indexed document.
Precomputed stacks.
- Store a stack of 200 candidate IDs (8 bytes each) per recently active user: 20M × 200 × 8 B = 32 GB, which fits comfortably in a Redis cluster.
Swipe history for filtering.
- An average user with 1 year of history at 100 swipes per day has about 36,500 swiped IDs. A heavy multi-year user can exceed 100,000.
- An exact set of 100,000 IDs at 8 bytes is 800 KB. A Bloom filter at 1 percent false positives needs about 9.6 bits per item, about 120 KB. Holding filters only for heavy users (say 10 percent of DAU, 2 million users × 120 KB) is about 240 GB, which is feasible in a Redis cluster. Light users are filtered exactly.
| Quantity | Value |
|---|---|
| Swipes per day | 2 to 4 billion |
| Swipe write QPS | ~23k average, 70k to 140k peak |
| Swipe storage | ~200 GB/day raw, ~220 TB/year replicated |
| Stack requests | ~1.2k/s average, ~4k/s peak |
| Matches | ~7 to 13 million/day |
| Search index | ~100 GB |
| Precomputed stacks | ~32 GB |
| Bloom filters for heavy users | ~240 GB |
The key observation: the swipe path is write-dominated and needs per-pair atomicity, while the feed path is read-latency-dominated and needs complex filtering. They should be separate services backed by different stores.
Core Entities#
- User / Profile: a person using the app, and also a profile shown to others. It holds age, gender, bio, photos (by reference) and the current location. Users swipe on users, so here "user" is a real entity rather than an implied actor.
- Preferences: the age range, gender(s) of interest, maximum distance and optional interest filters. They are used to build the user's stack and, in reciprocal matching, to decide whether the user should appear in others' stacks.
- Swipe: a "yes" or "no" decision, belonging to a swiping user and about a target user, with a timestamp.
- Match: a connection between two users who both swiped yes on each other, with a creation time. It is the start of a chat.
- Stack (feed): an ordered, precomputed list of candidate user IDs for a user, with a build time and the location and preferences it was built for.
- Seen filter: a per-user structure (an exact set, or a Bloom filter for large histories) of everyone the user has swiped on.
API Design#
All endpoints require authentication. The caller's identity always comes from the validated session token or JWT, never from a user ID in the body or headers, which a client could forge (see Authentication and Authorization and API Design Best Practices).
# Create or update profile preferences (photos and bio handled by other endpoints)
POST /profile
{ "age_min": 20, "age_max": 30, "distance": 10,
"interested_in": "female" | "male" | "both", "interests": ["hiking", "jazz"] }
-> 200 { profile }
# Get a stack of candidates near the current location
GET /feed?lat={lat}&long={long}&distance={miles}
-> 200 { "profiles": [ { userId, name, age, photos[], distanceBucket, ... } ] }
# Swipe on a profile; the path names the TARGET, the token names the SWIPER
POST /swipe/{targetUserId}
{ "decision": "yes" | "no" }
-> 200 { "match": null | { matchId, userId, createdAt } }
# List matches (used by the chat surface)
GET /matches?cursor={c}
-> 200 { matches: [...], nextCursor }Design notes:
- Preferences live on the server. The feed endpoint does not need age or interest filters in the query, because the server loads the saved preferences. Location and distance travel with the request, because location changes constantly and the client knows it best.
- No pagination on the feed. It is a recommendation stream, not a fixed list. When the client runs low, it simply calls
GET /feedagain for more. Cursor pagination does apply toGET /matches, which is a stable list. - Consistent filter conventions. If other list endpoints accept filters (for example
GET /matches?status=active&sort=-createdAt, where a leading minus means descending), use the same parameter names and sort syntax everywhere. Clients that learn one endpoint's conventions assume they hold for all. - Swipes are naturally idempotent. The pair (swiper, target) is the natural key, so a retried swipe overwrites the same record rather than creating a duplicate (see Idempotency and Safe Retries). The response includes the match, if any, so the client can show "It's a match!" immediately.
- Distance is returned as a bucket ("2 miles away"), never exact coordinates, which protects users' locations (Deep Dive 11).
High-Level Design#
We satisfy the functional requirements one at a time with the simplest design that works. Then the deep dives fix the performance and consistency problems we knowingly leave behind.
1. Create a profile with preferences#
This is a plain client, service and database path.
- The client sends
POST /profilewith the preferences. - The API Gateway authenticates the request and routes it to the Profile Service (see API Gateway and Backend-for-Frontend).
- The Profile Service validates the input (age range sane, distance within limits) and writes it to the Profile DB.
- The response returns to the client.
A relational database such as PostgreSQL fits here (see PostgreSQL in Practice). Profiles are structured, moderately sized (100 million rows) and updated rarely, and we want constraints and transactions for account data.
2. View a stack of potential matches#
When the user opens the app, they expect a stack of profiles that fits their filters (age, gender, interests) and lies within their maximum distance (for example under 2, 5 or 15 miles).
The simplest implementation queries the Profile DB directly:
SELECT * FROM users
WHERE age BETWEEN 18 AND 35
AND gender = 'female'
AND lat BETWEEN :userLat - :dLat AND :userLat + :dLat
AND long BETWEEN :userLong - :dLng AND :userLong + :dLng
LIMIT 200;- The client calls
GET /feed?lat=..&long=..&distance=... - The gateway routes the request to the service that builds feeds (for now, the Profile Service).
- The service loads the user's preferences and runs the query.
- The results return to the client.
This works for a demo and fails at scale:
- A B-tree index on
latcan narrow only one dimension. Thelongrange is then checked row by row across a whole band of latitude around the planet. - Combining that with age and gender filters on 100 million rows takes far more than 300 ms.
- It does nothing about excluding people already swiped on.
Deep Dives 3 to 6 replace it with a geo-indexed search engine plus precomputed stacks.
3. Swipe right or left#
We add two components: a Swipe Service, which persists swipes and checks for matches, and a Swipe DB.
Why a separate service and a separate database? Swipes are about 2 billion writes per day, while profile edits are a tiny fraction of that. Separating them lets the swipe path:
- scale independently;
- use a write-optimised store;
- have its own caching and consistency logic, without endangering profile data.
The Swipe DB should be built for massive write throughput and simple key access. Apache Cassandra is a good fit (see Apache Cassandra in Practice). Its storage engine appends every write to a commit log, buffers it in an in-memory memtable, and flushes sorted, immutable SSTables to disk. This is an LSM tree (see Storage Engines: B-Trees vs LSM Trees), so writes are sequential and cheap.
- Partition by
swiping_user_id, so "all of A's swipes" and "did A swipe on B?" are single-partition reads. - Cluster by
target_user_idwithin the partition.
- The client sends
POST /swipe/{targetUserId}with the decision. - The gateway routes the request to the Swipe Service.
- The Swipe Service writes the swipe to the Swipe DB.
- It checks for the inverse swipe (did the target already swipe yes on the swiper?). If found, it returns a match.
The weakness is that Cassandra is eventually consistent by default, and "write, then check the inverse" is not atomic across the two users' partitions. Deep Dive 1 fixes this.
4. Match notifications#
Call the first person to swipe yes A and the second B.
- Notifying B is already done. B's swipe is the one that completes the match, so the Swipe Service returns the match in the response, and B's app shows "It's a match!" at once.
- A may have swiped weeks ago and is probably not in the app. A needs a push notification through the platform services: Apple Push Notification service (APNs) for iOS and Firebase Cloud Messaging (FCM) for Android. The app holds a device token for each device; our Notification Service calls APNs or FCM with the token and a payload.
The full swipe sequence:
- Some time ago, A swiped yes on B. That swipe was stored.
- B swipes yes on A.
- The server checks for the inverse swipe and finds A's yes.
- B's app shows "You matched!" immediately.
- A match event is published. The Notification Service sends a push to A through APNs or FCM.
The details of match storage and the chat that follows are outside our scope. We assume an external push service exists and say so to the interviewer.
The full high-level design#
After the deep dives, the design looks like this:
Components:
- Mobile client: keeps a buffer of the current stack and a cache of its recent swipes. It requests a refill before the stack runs out and filters out anything it has just swiped.
- API Gateway: handles authentication, per-user rate limits and routing.
- Profile Service and Profile DB (PostgreSQL): the source of truth for profiles, preferences and last location.
- CDC to the search index: profile and location changes flow through change data capture into Elasticsearch, which indexes
geo_pointlocations plus filterable fields (see Change Data Capture and the Outbox Pattern and Elasticsearch and Search Systems). - Feed Service: returns the precomputed stack from the stack cache (Redis), and falls back to a real-time search when the stack is missing, stale or exhausted.
- Feed Builder workers: periodically, or when triggered, compute stacks for recently active users by querying the index, excluding seen profiles, ranking, and writing to the stack cache.
- Swipe Service: records the swipe and atomically checks for the reciprocal yes, using Redis Lua scripts on a pair key (Deep Dive 1). It publishes swipe and match events to Kafka.
- Swipe DB (Cassandra): the durable, write-optimised swipe history.
- Seen filters: exact sets for light users and Bloom filters for heavy users, updated from the swipe stream.
- Notification Service and Match store: persist matches and push them to the first swiper.
Key Flows#
Flow 1: Open the app and load the stack#
- The client calls
GET /feedwith its current location and distance. - The Feed Service reads the user's precomputed stack from Redis, together with its metadata (when it was built, and for which location and preferences).
- If the stack exists, is younger than its TTL (for example 30 to 60 minutes), was built within a short distance of the current location, and used the current preferences, the service takes the next 50 to 100 IDs. It runs a quick serve-time check on them: still active, not blocked, not already swiped according to the seen filter. It then hydrates them into profile cards from a profile cache and returns them. That takes about 10 to 30 ms.
- If the stack is missing or stale, the service runs a real-time search against Elasticsearch (geo plus filters plus exclusions), returns the first page of results at once, and asks the Feed Builder to build a full stack in the background. That takes about 80 to 200 ms.
- The client shows the cards. When the user has about 50 cards left (for example card 150 of 200), the client requests more in the background, so the stack feels endless.
Flow 2: Swipe right, and it is a match#
- B swipes yes on A. The client animates the card away instantly and sends
POST /swipe/Awithdecision=yes. - The Swipe Service computes the pair key from the two sorted IDs,
swipes:A:Bif A sorts first. - It runs a Lua script in Redis that atomically records B's decision in the pair hash and reads A's decision (Deep Dive 1). Because the script runs atomically on the shard that owns the key, no other swipe on this pair can interleave.
- A's field says yes, so it is a match. The Swipe Service creates the match idempotently, with a match ID derived from the pair, so a duplicate attempt is harmless.
- It publishes
SwipeRecordedandMatchCreatedevents to Kafka. Consumers write the swipe to Cassandra, update B's seen filter, persist the match and notify A. - The response tells B's client about the match, which shows "It's a match!".
Flow 3: Simultaneous swipes, the race the design must survive#
- A swipes yes on B, and B swipes yes on A, within the same few milliseconds, on different Swipe Service instances.
- Both instances compute the same pair key, so both scripts go to the same Redis shard and run one after the other. Redis executes scripts one at a time.
- Suppose A's script runs first. It sets A's field and reads B's field, which is empty, so there is no match yet.
- B's script runs second. It sets B's field and reads A's field, which is yes, so it is a match. B sees it immediately, and A gets a push notification a moment later.
- There is no interleaving in which both scripts read an empty field, which is exactly the failure that a non-atomic "check, then write" allows.
Flow 4: A profile or location change keeps stacks honest#
- A user moves to another neighbourhood and opens the app. The client sends the new location with
GET /feed, and the Profile Service also records it. - The Profile DB change flows through CDC into Elasticsearch. The update is batched, because the search engine prefers bulk writes, and becomes visible after the index refresh interval (around 1 second).
- The Feed Service sees that this user's own stack was built about 8 km away, which is outside a drift threshold. It treats the stack as stale and serves a fresh search.
- Other users' stacks that already contain this person are not rebuilt immediately. Their serve-time check re-validates candidates against the current profile cache (still in range, still within filters, still active) before showing them. Mismatches are dropped silently.
Data Model#
Physical layout per store.
-- Cassandra: durable swipe history, one partition per swiper
CREATE TABLE swipes_by_swiper (
swiper_id bigint,
target_id bigint,
decision text, -- 'yes' | 'no'
created_at timestamp,
PRIMARY KEY ((swiper_id), target_id)
);
-- Cassandra: matches listed per user (written twice, once for each side)
CREATE TABLE matches_by_user (
user_id bigint,
created_at timestamp,
match_id text, -- 'low:high', deterministic from the pair
other_id bigint,
PRIMARY KEY ((user_id), created_at, match_id)
) WITH CLUSTERING ORDER BY (created_at DESC, match_id ASC);# Redis: per-pair state for atomic match detection (key = sorted pair)
HASH swipes:{low}:{high} fields: "{low}" -> yes|no, "{high}" -> yes|no TTL ~ 30-90 days
# Redis: precomputed stack per user
LIST stack:{userId} candidate IDs, newest build first
HASH stackmeta:{userId} built_at, lat, lng, prefs_hash
# Redis: seen filter for heavy users (RedisBloom)
BF seen:{userId} Bloom filter of swiped target IDs| Data | Store | Why |
|---|---|---|
| Profiles, preferences, last location | PostgreSQL (sharded by user ID if needed) | Structured, transactional, moderate size, source of truth |
| Searchable profile documents | Elasticsearch / OpenSearch | Geo plus multi-field filters plus ranking in one query |
| Swipe history | Cassandra | Billions of writes per day, partition per swiper, cheap sequential writes |
| Pair state for matching | Redis Cluster | Atomic per-key scripts, sub-millisecond latency |
| Precomputed stacks | Redis | Small, hot, rebuilt often, TTL-friendly |
| Seen filters | Redis sets or Bloom filters | Fast membership checks during build and serve |
| Matches | Cassandra (per-user listing), plus an event to the chat system | Append-heavy, listed per user |
| Swipe and match events | Kafka | Decouples the hot path from storage, notifications and analytics |
For how to reason about these choices in general, see Choosing a Database: A Decision Guide.
Notes on the model:
- The pair key always sorts the two IDs. A's swipe on B and B's swipe on A must land on the same key, and hence the same shard, for atomicity.
swipes:123:456is the same key whichever of the two swipes. - Swipes are stored by swiper in Cassandra, because the durable access pattern is "everything A swiped" (for rebuilding seen filters) and "did A swipe on B?" (for fallbacks). The pair view in Redis serves only the real-time match check.
- The match ID is deterministic (
low:high). Creating the same match twice is an idempotent upsert, not a duplicate. - Ages are derived from the birth date at query time or in the index, so they never go stale.
Deep Dives#
1. Consistent match detection: closing the mutual-swipe race#
The failure. The high-level design checks for the inverse swipe and then writes its own. Consider A and B swiping yes on each other at nearly the same moment:
- A's request checks for B's yes. Nothing is there.
- B's request checks for A's yes. Nothing is there.
- A's swipe is saved.
- B's swipe is saved.
Both swipes are now stored, but neither request detected the match. Nobody is notified, and the two people each conclude the other was not interested. This is the classic check-then-act race (see Concurrency Control and Database Locking). Swapping the order inside each request to "write, then check" helps (more on that below), but on an eventually consistent store, even that is not enough without care.
Option 0: give up strong consistency and reconcile. You could accept the race and run a periodic reconciliation job that finds pairs with mutual yeses but no match, creates the match, and notifies both users. They would never know the match was detected late; each assumes the other just swiped. This favours availability over consistency (see CAP Theorem and PACELC) and is a legitimate trade-off to raise. But it removes the instant "It's a match!" moment for the second swiper, which is the product's core dopamine hit. Most interviewers will appreciate the discussion and ask you to keep strong consistency. Keep the reconciler anyway, as a safety net (Deep Dive 9).
Bad: poll the database for reciprocal swipes. A background job scans for mutual yeses every few minutes and creates matches. It fails the "notify immediately" requirement outright, and frequent scans over billions of rows put heavy, pointless load on the database. It is worth one sentence, as a non-starter.
Good: a database transaction. Put "save my swipe" and "check for the reciprocal swipe" in one atomic transaction, so concurrent transactions on the same pair serialise. The problem is scale and placement. At 2 billion swipes per day the data is spread over many partitions. With the natural layout (partition by swiper), A's swipe and B's swipe live in different partitions, so the transaction is cross-partition.
- Cassandra offers lightweight transactions (LWT): conditional writes (
IF NOT EXISTS,IF col = value) that run a Paxos consensus round among replicas. They give linearizable behaviour, but only within a single partition. There are no multi-partition atomicity, isolation levels or rollbacks, and each LWT costs several round trips between replicas, roughly four times the latency of a normal write. - A general distributed transaction across partitions (two-phase commit, see Distributed Transactions: 2PC, Sagas and Outbox) would work in principle, but it is heavy for 70,000 operations per second.
Great: put both directions of a pair in the same partition. The key move is to co-locate both users' swipes about each other. Partition by a pair key formed from the two sorted IDs: user_pair = min(a, b) : max(a, b). A → B and B → A then land in the same partition, and a single-partition operation can be atomic.
CREATE TABLE pair_swipes (
user_pair text, -- 'low:high', sorted
low_dir text, -- decision of the lower ID: 'yes' | 'no' | null
high_dir text, -- decision of the higher ID
PRIMARY KEY ((user_pair))
);
-- Swipe by the lower ID, using an LWT so the pair row is updated linearizably:
UPDATE pair_swipes SET low_dir = 'yes' WHERE user_pair = :p IF low_dir = null;
-- then read the other side at SERIAL consistency (sees any committed LWT):
SELECT high_dir FROM pair_swipes WHERE user_pair = :p; -- consistency SERIALA note on a common shortcut: a Cassandra BATCH cannot contain a SELECT, so "insert and read in one batch" is not a real mechanism. The atomicity comes from LWTs on the pair partition, or from the ordering argument below.
Why "write mine, then read theirs" is enough under linearizability. Each request does W (write my yes) and then R (read the other's field). Suppose both requests miss each other:
- A's read missed B's write, so in the linearizable order R_A came before W_B.
- B's read missed A's write, so R_B came before W_A.
- Each request also writes before it reads: W_A before R_A, and W_B before R_B.
- Chaining these gives W_A < R_A < W_B < R_B < W_A, which is a cycle and therefore impossible.
So at least one request sees the other's yes. Both may see it, in which case both try to create the match. The match ID is deterministic (low:high) and the insert is IF NOT EXISTS, or an upsert, so the duplicate is harmless. Notifications are deduplicated by match ID.
The same argument works with plain Cassandra QUORUM writes and QUORUM reads (strict quorums, R + W > N), even without LWT. A quorum read that starts after a quorum write completed is guaranteed to see it. If A's read missed B's write, B's write completed after A's read began, which is after A's write completed. So B's read, which started after B's write completed, sees A's write. This is cheaper than LWT, but it relies on strict quorums. Never use consistency ONE here.
The pair-partition design has operational costs:
- The pair table holds one row per pair ever swiped, which is billions of rows. Rows are tiny, but they need a TTL or archival policy: a pair where one side said no long ago can expire.
- Hot users (very popular profiles) are spread across many pair keys, so there is no single hot partition. This is a quiet advantage over partitioning by target.
Great alternative: Redis for the atomic check, Cassandra for durability. Redis executes each command, and each Lua script, atomically on the shard that owns the key, with nothing interleaving. With a hash per sorted pair:
-- KEYS[1] = "swipes:{low}:{high}"
-- ARGV[1] = my field, ARGV[2] = my decision, ARGV[3] = other field, ARGV[4] = ttl seconds
redis.call('HSET', KEYS[1], ARGV[1], ARGV[2])
redis.call('EXPIRE', KEYS[1], ARGV[4])
return redis.call('HGET', KEYS[1], ARGV[3]) -- other side's decision or nilThe Swipe Service calls the script. If my decision is yes and the returned value is yes, it is a match. Redis Cluster maps every key to one of 16,384 hash slots, and the whole script touches a single key, so it always runs on exactly one shard. The cluster scales horizontally by adding shards and moving slots (see Redis in Practice). Latency is sub-millisecond.
The trade-offs of the Redis approach, and their fixes:
- Durability: Redis replication is asynchronous, so a failover can lose the last few acknowledged writes. Mitigate in four ways:
- Publish every swipe to Kafka, and from there to Cassandra, as the durable record.
- Optionally use
WAIT 1 <timeout>after the script, so at least one replica has the write before acknowledging. This narrows the loss window but does not make Redis a consensus store. - If a pair key is missing (lost or expired), fall back to a Cassandra point read of the other side,
swipes_by_swiper(target, me). - Keep the reconciler as the last line of defence.
- Memory: store only yes decisions in Redis. A "no" on either side means no match is possible, so the check never needs it. About 670 million likes per day at roughly 100 bytes each is about 67 GB per day, so a 7-day TTL needs about 470 GB, and a 30-day TTL about 2 TB. The TTL is a tunable trade-off: a shorter TTL means more Cassandra fallbacks for old likes.
- The fallback path must be ordered correctly too. On a Redis miss, write the yes to Redis first (so later swipers find it), then read Cassandra for the other side. If an old like is found there, it is a match. Two concurrent requests on a cold pair both write to Redis first, so the atomic script protects them as before.
Other stores that give the same guarantee.
- DynamoDB: a pair item with a conditional update. Set my attribute, use
ReturnValues=ALL_NEW, and check the other attribute. Each update on one item is atomic (see Amazon DynamoDB in Practice). - Sharded PostgreSQL: shard by the pair key and use
INSERT ... ON CONFLICT DO UPDATE ... RETURNING, orSELECT ... FOR UPDATEon the pair row.
The principle is always the same: make both directions of a pair one unit of atomicity.
2. Swipe write volume: absorbing tens of thousands of writes per second#
The load. About 23,000 swipes per second on average and 70,000 to 140,000 at peak, each a tiny write, adding about 200 GB per day. Every design choice here aims to make each swipe cheap, sequential and partition-local (see Pattern: Scaling Writes).
Why an LSM store. In a B-tree database, every insert updates pages in place, which means random I/O and write amplification under heavy insert load. In Cassandra's LSM engine:
- A write appends to the commit log (sequential).
- It goes into the in-memory memtable.
- The write is acknowledged.
- Memtables flush to immutable sorted SSTables.
- Background compaction merges SSTables.
A single node commonly sustains tens of thousands of small writes per second. A cluster of a few dozen nodes, with a replication factor of 3, handles 140,000 swipes per second with headroom (see Storage Engines: B-Trees vs LSM Trees).
Partitioning.
swipes_by_swiperpartitions byswiper_id. Writes spread evenly across the cluster, because there are tens of millions of swipers.- A partition grows by about 100 rows per day for a typical user. After a year that is about 36,500 rows of around 50 bytes each, roughly 2 MB, comfortably under the guidance of keeping partitions below roughly 100 MB.
- Extreme users, such as bots or someone who swipes all day for years, can be bucketed:
PRIMARY KEY ((swiper_id, year), target_id). That keeps any single partition bounded.
Compaction and TTL.
- "No" swipes matter only to stop repeats. Many products let old passes resurface after months, so give "no" rows a TTL (for example 6 to 12 months) and keep "yes" rows longer.
- Expiring rows become tombstones. Choose a compaction strategy and
gc_grace_secondsthat keep tombstones from piling up. Time-bucketed data with uniform TTLs suits time-window compaction. Per-swiper partitions that are read back often suit levelled compaction. - The exact choice should come from a benchmark on real data, not from a rule of thumb.
Kafka in front of the database. The Swipe Service does the latency-critical part synchronously: the atomic pair check in Redis, plus appending a SwipeRecorded event to Kafka with acks=all. The durable write to Cassandra, the seen-filter update and the analytics happen in consumers.
- Kafka absorbs bursts. A Cassandra slowdown becomes consumer lag, not user-facing errors.
- Kafka is partitioned by
swiper_id, so each user's swipes are processed in order. - Consumers write to Cassandra in small batches, unlogged and same-partition, which reduces per-write overhead.
- The swipe is durable once Kafka acknowledges it, because Kafka is replicated (see Apache Kafka in Practice).
Client-side batching for passes. Left swipes do not affect matches. The client can batch several "no" decisions and send them every few seconds, or when the app goes to the background. That reduces request count, not data volume. Right swipes are sent individually and immediately, because they may complete a match. The client must keep unsent passes in local storage, so a crash does not lose them. A lost pass only means a repeat later, which is a minor annoyance.
Derived counters with fewer writes. Some features need aggregates, such as how many likes a profile received this week (an input to ranking). Writing a counter increment for every like would double the write load and create hot keys for popular profiles. There are two standard techniques:
- Batch increments. A stream job aggregates likes per profile over a window (for example 30 seconds) and applies one increment of +N. This helps hot profiles, but it does not reduce writes for the long tail, where a profile receives one like per window anyway.
- Milestone updates. Update the searchable "popularity" field only when the count crosses thresholds, such as powers of 2 (1, 2, 4, 8 and so on). Writes then grow logarithmically in the count: about 10 index writes for 1,000 likes instead of 1,000. The indexed value is approximate (call it
approxLikes, so nobody mistakes it for exact), but ordering by it is roughly right. When precision matters, fetch the top 2N candidates by the approximate value and re-rank them with exact counts from a counter store.
This two-stage pattern, an approximate index followed by precise re-ranking, is common in search and recommendation systems.
Rate limits and abuse. A bot can swipe yes on everyone, which creates load and spam matches. Apply per-user rate limits at the gateway (see Rate Limiting and Throttling). Many dating products also cap daily likes for free accounts, which shapes behaviour as well as load. Flag accounts with inhuman swipe cadence or a 100 percent like ratio for review.
3. Geo filtering: "within N miles" plus preferences, fast#
Why the naive query fails. lat BETWEEN ... AND long BETWEEN ... with B-tree indexes can use one index for one range. The database scans every row in a latitude band (a strip around the whole planet), then filters by longitude, age and gender. With 100 million users, the band around a big city's latitude contains millions of rows. Even a composite index helps only the first range column (see Database Indexing). Two-dimensional proximity needs a spatial index (see Geospatial Indexing and Proximity Search).
Spatial index options.
- Geohash: encode latitude and longitude into a string whose prefix identifies a grid cell. Nearby points mostly share prefixes, so "within 5 miles" becomes a few prefix ranges (the cell plus its neighbours) on an ordinary B-tree, followed by an exact distance check. Redis GEO commands store geohash-derived scores in a sorted set and support radius queries.
- Quadtree: recursively split space into four until each cell holds at most K points. It adapts to density: tiny cells in Manhattan, huge cells in rural areas.
- BKD trees: Elasticsearch indexes
geo_pointfields with a BKD tree, a disk-friendly variant of the k-d tree. That makesgeo_distanceandgeo_bounding_boxfilters fast, and they can be combined with other filters in one query. - PostGIS GiST indexes on PostgreSQL geography columns support
ST_DWithinradius queries well at moderate scale.
For this problem, the winner is a search engine (Elasticsearch or OpenSearch). We need geo, ranges, term filters and ranking in one query, at thousands of QPS, over about 100 GB of documents.
The query, including reciprocal preferences. A good stack shows B to A only if B fits A's filters and A fits B's filters. Otherwise A sees people who would never be shown A, which wastes swipes on both sides.
{
"size": 300,
"query": { "bool": {
"filter": [
{ "geo_distance": { "distance": "10mi", "location": { "lat": 40.73, "lon": -73.99 } } },
{ "range": { "age": { "gte": 25, "lte": 34 } } },
{ "terms": { "gender": ["female"] } },
{ "term": { "interested_in": "male" } },
{ "range": { "pref_age_min": { "lte": 29 } } },
{ "range": { "pref_age_max": { "gte": 29 } } },
{ "term": { "status": "active" } },
{ "range": { "last_active_at": { "gte": "now-14d" } } }
],
"must_not": [ { "ids": { "values": ["<recently swiped ids>"] } } ]
} }
}In the query, the viewer is a 29-year-old man looking for women aged 25 to 34 within 10 miles. The pref_age_* and interested_in terms check that the viewer fits each candidate's preferences.
The candidate's own maximum distance is the only reciprocal filter that is awkward: it depends on the distance between the two people. There are three ways to handle it:
- a script filter, which is slow;
- index each user's max distance into a few buckets and filter by bucket (approximate);
- over-fetch, then post-filter exactly in the Feed Service. Over-fetching a little and post-filtering is simplest.
Filter context is cheap. Clauses in filter do not compute relevance scores, and Elasticsearch caches their results as bitsets. Filters such as status: active and gender get reused across queries.
Ranking happens in a separate step (Deep Dive 7), so the search only produces a candidate set of a few hundred.
Index sharding. Most queries are local, so there are two choices:
- Route by region: each shard holds one metro area or a geohash prefix range, and the query goes only to that shard. This is cheap per query, but dense cities make shards uneven, and people near region borders need multi-shard queries.
- Spread documents evenly across shards and fan every query out. This is simpler and well-balanced, but every shard does work for every query.
At about 4,000 stack queries per second and a 100 GB index, an evenly sharded cluster with replicas is fine. Region routing is an optimisation for larger scale.
Keeping the index fresh.
- Location updates (about 1,200 per second) and profile edits flow from the Profile DB through CDC to Elasticsearch. Use the bulk API with small batches (for example every 1 second or 500 documents), because Elasticsearch handles writes best in bulk.
- A refresh interval of 1 to 5 seconds keeps new locations searchable quickly without the indexing overhead of real-time refresh.
- A small lag is acceptable: someone who moved 5 minutes ago may appear in a stack based on their old location, and the serve-time check catches large mismatches.
Location cadence and privacy.
- Update location on app open and when it moves significantly (for example more than 1 km). Never track continuously in the background for this product.
- Round stored coordinates for search, for example to around 100 m, or snap them to a geohash cell.
- Never return exact coordinates or exact distances to other users. Show buckets ("less than 1 mile", "3 miles").
Security researchers have demonstrated trilateration attacks on location-based apps that return precise distances: they measure the distance from three fake positions and intersect the circles. Coarse buckets, server-side rounding and limits on how quickly an account can change its location all defeat this.
4. The precomputed recommendation stack: instant first card, endless feel#
Users open the app wanting to swipe immediately. Even a well-indexed search with ranking and exclusions takes 80 to 200 ms, and at the evening peak, thousands of these heavy queries per second strain the cluster. There are three approaches, each building on the last.
Good: query an indexed search engine in real time. Build every stack on demand with the geo plus filters query from Deep Dive 3.
- Pros: results are always fresh (current locations, current preferences); there is nothing to precompute or store; it is simple.
- Cons: every app open pays the full query cost and latency. The search cluster must be sized for the peak query rate. The primary database and the index must be kept in sync through CDC, with batching because the index is read-optimised.
Good: precompute stacks and cache them. Background jobs build stacks for users ahead of time and store them in Redis. Opening the app is then a single cache read of about 1 to 5 ms.
- Pros: instant loads, and the expensive work can be spread over off-peak time.
- Cons:
- Heavy swipers exhaust the cached stack in minutes. Without a plan, they hit the slow path just when they are most engaged.
- The stack can be stale: candidates may have moved or changed preferences, and new users who joined after the build are missing.
- Precomputing for every user is wasteful, because many will not open the app before the stack expires.
Great: combine precomputation with real-time search.
- Precompute for likely-active users only. Warm stacks for users active in the last day or so, ideally just before their usual active time (many users open dating apps in the evening). Inactive users get a real-time stack on their next open.
- Serve the cached stack instantly on app open, after the serve-time check.
- Refill before empty. When the client has about 50 cards left, it asks for more. The Feed Service runs a real-time search (excluding everything in the current stack and the seen filter) or triggers the Feed Builder, so the new batch arrives before the user reaches the end. As far as the user can tell, the stack is infinite.
- Rebuild on triggers (Deep Dive 5): the user changes preferences, moves far, or the stack's TTL expires.
The stack is a tunable system. Several knobs change cost and quality without changing the architecture:
| Parameter | Typical starting value | Effect of raising it |
|---|---|---|
| Stack TTL | 30 to 60 minutes | Cheaper (fewer rebuilds), but staler |
| Stack size | 100 to 300 profiles | Fewer refills for heavy users, more wasted work for light ones |
| Warm-set definition | Active in last 24 to 48 hours | Better hit rate, more precompute cost |
| Refill threshold | 25 to 30 percent remaining | Smoother experience, more early queries |
| Drift threshold for location | 2 to 5 km | Fewer rebuilds when users move slightly |
Being able to tune these in production, by watching cache hit rate, stack exhaustion events and cost, is a sign of a mature design. Say this explicitly in an interview.
Feed Builder mechanics.
- Workers consume a queue of build jobs: scheduled warm-ups, triggered rebuilds and refills.
- For each user, a worker:
- loads the preferences and last location;
- queries the index for about 500 candidates;
- removes seen IDs using the user's seen filter;
- applies the post-filters;
- ranks the candidates;
- writes the top 200 to
stack:{userId}with metadata (built_at, the location and a hash of the preferences).
- Jobs are idempotent and deduplicated per user, so a burst of triggers produces one rebuild.
Cost check. Warming 20 million stacks once per evening at about 100 ms of search time each is about 2 million search-seconds. Spread over 2 hours, that is about 280 concurrent queries. That load is comparable to the real-time peak, but it is predictable and shifted earlier, which is easier to provision.
Multiple devices. We assume one active device per user. The client cache and the server stack are per user, so a second device would simply request its own refill. Swipes on either device update the shared seen filter, so repeats are still avoided after a short lag.
5. Stale stacks: what goes wrong and how to contain it#
A cached stack is a snapshot. A profile in it is stale if it no longer fits the viewer's filters, or should no longer be shown at all.
Stale because the candidate changed.
- The candidate moved and is now outside the viewer's distance.
- The candidate changed their profile or preferences (age range, interested-in), so the reciprocal filter fails.
- The candidate paused, deleted or was banned, or blocked the viewer.
Stale because the viewer changed.
- The viewer changed their filters (for example narrowed the age range).
- The viewer moved significantly (a different neighbourhood or city).
Containment strategies, layered.
- Short TTL (under an hour) bounds how old any stack can be.
- Viewer-side triggers: a preference change or a large location change (beyond the drift threshold) invalidates the user's own stack and enqueues a rebuild. The next open, or the next refill, gets fresh results. Ideally the rebuild runs in the background right after the change, because the user will probably start swiping soon.
- Serve-time validation for candidate-side changes. Rebuilding everyone's stacks whenever one candidate moves is impossible: a candidate can sit in thousands of stacks. Instead, before returning each card, the Feed Service checks the candidate against a profile cache (current coarse location, status, preferences hash, block lists). It drops cards that fail, which is a few microseconds per card. This is cheap because it is a key lookup per card, not a search.
- Hard removals are pushed, not polled. Bans, deletions and blocks must take effect immediately for safety. They go into a fast-access deny set that is checked at serve time, and the client is told to drop the card if it already holds it.
Cost trade-off. Very short TTLs with eager rebuilds keep stacks fresh but multiply builder load. Long TTLs with serve-time validation are cheap, but they shrink the effective stack size as candidates are dropped. Monitor the drop rate at serve time: if 30 percent of cached cards are being dropped, the TTL is too long or the builder is not reacting to triggers.
6. Never show someone twice: exact checks, client cache and Bloom filters#
Re-showing a profile the user already swiped on is a bad experience. After a "yes", it suggests the like was not recorded. After a "no", it is just annoying. Every stack must exclude the user's entire swipe history, which for heavy users is tens of thousands of IDs or more.
Bad: query the swipe DB and do a contains check. When building a stack, read every target ID in the user's Cassandra partition, then drop candidates that appear in it. Reading one partition is efficient, but there are two problems:
- Recent swipes may be missing. With an availability-leaning configuration (for example writes and reads at consistency
ONE, or swipes still sitting in Kafka waiting for the consumer), swipes from the last few seconds may not be visible in the replica being read. Those profiles come back. - Large histories make it slow. Reading 100,000 rows to build every stack is megabytes of I/O per build, and a contains check against a set that big, repeated for every candidate, adds up. It gets worse the more the user swipes, so the cost grows with exactly the most engaged users.
Great: add a client-side cache of recent swipes. The two gaps above share a cause: the newest swipes are the ones that have not "landed" everywhere yet. The client knows them for certain, because it made them. So the client keeps its last K swipes (for example the last 1,000 IDs) locally and drops any card in a new batch that appears there. We can lean on the client because we assume one active device per user.
This is especially useful during refills. Imagine a user working through 200 prefetched profiles:
- At around card 150, the client asks the backend to build a new batch.
- It fetches the batch when ready.
- It filters out any profile the user swiped in the meantime, including swipes made after the backend started building.
A server-side cache just to cover replication lag would cost memory and complexity. The client cache costs nothing and covers exactly the right window. What remains is the cost of large histories on the server.
Great: add a Bloom filter for large histories. A Bloom filter is a bit array of m bits with k hash functions (see Probabilistic Data Structures for Big Data).
- Insert an ID by setting the k bits it hashes to.
- Query an ID by checking its k bits. If any bit is 0, the ID was definitely not inserted. If all are 1, it was probably inserted.
- False negatives are impossible. False positives happen at a tunable rate.
For this problem, the asymmetry is exactly right:
- No false negatives means we never re-show someone the user swiped on, which is the requirement.
- A false positive means we wrongly think the user swiped on someone, so that person is never shown. At a 1 percent rate, 1 in 100 unseen candidates is silently skipped. In a dense city that is invisible. In a sparse rural area with few candidates it matters more, so choose a lower rate there, or skip the filter for small candidate pools.
Sizing. For n items and a target false-positive rate p:
- the optimal number of bits is m = −n × ln p / (ln 2)², which is about 1.44 × log₂(1/p) bits per item;
- the optimal number of hashes is k = (m / n) × ln 2.
| Target p | Bits per item | Hashes k | Size for 100,000 swipes |
|---|---|---|---|
| 1% | ~9.6 | 7 | ~120 KB |
| 0.1% | ~14.4 | 10 | ~180 KB |
| 0.01% | ~19.2 | 13 | ~240 KB |
Compare this with an exact set of 100,000 eight-byte IDs: about 800 KB raw, and more in a general-purpose hash set.
Who gets a Bloom filter. Only users whose history exceeds a threshold (say 5,000 to 10,000 swipes). Below it, an exact set in Redis is small and has no false positives. Above it, build a Bloom filter. This keeps total memory at a few hundred GB (see Capacity Estimation) and keeps checks fast: k bit lookups per candidate, regardless of history size.
Operating the filters.
- Updates: a Kafka consumer of
SwipeRecordedevents adds each target ID to the swiper's filter. RedisBloom (part of Redis Stack) providesBF.ADD,BF.MADDandBF.EXISTSnatively. Without the module, implement the filter withSETBITandGETBITon a Redis string, or keep it in the Feed Builder's memory for the duration of a build. - Growth: a filter sized for 50,000 items degrades once it holds 200,000. Scalable Bloom filters (Paulo Sérgio Almeida, Carlos Baquero, Nuno Preguiça and David Hutchison, "Scalable Bloom Filters", Information Processing Letters, 2007) add a new, larger sub-filter with a tighter error rate when the current one fills, so the compound false-positive rate stays bounded. RedisBloom supports this through its expansion setting.
- Deletion: standard Bloom filters cannot delete. If old passes should resurface after six months, use time-partitioned filters, one per month, and drop the oldest. A query checks all of the live months. Counting Bloom filters, which use small counters instead of bits, support deletion at about 4 times the memory.
- Recovery: if a Redis node is lost, its filters can be rebuilt by scanning each user's Cassandra partition. That is cheap per user, but expensive if millions of filters must be rebuilt at once. Mitigate with replicas and persistence for the filter shards, periodic snapshots of filters to object storage, and lazy rebuilds (rebuild a user's filter on their next stack build, and use the exact Cassandra check, plus the client cache, until then).
- This is arguably over-engineering for an interview. The client cache plus an exact server-side check is enough for most users. The Bloom filter is a legitimate optimisation for the heavy tail, and it is worth presenting that way, not as the default.
Other exact alternatives.
- Roaring bitmaps: if user IDs are dense 32-bit integers, a compressed roaring bitmap stores a sparse set exactly in roughly 2 bytes per member plus container overhead. That is somewhat larger than a 1 percent Bloom filter, but exact, and it supports fast intersection and difference.
- Exclusion inside the search query: Elasticsearch
must_notwith anidsortermsclause works for hundreds or a few thousand IDs. Term lists have a configurable maximum size (65,536 terms by default in recent versions), and big lists make queries slow. So exclude only the recent history in the query, and filter the rest in the Feed Service. - Over-fetch, then filter: ask the index for 3 to 5 times the needed candidates and filter afterwards. If the filter is very restrictive (a heavy user in a small town), you may still come up short. Then fetch again with a wider radius or a lower ranking threshold.
Bloom filters are already inside the database. Cassandra keeps a Bloom filter per SSTable, so a point read like "did A swipe on B?" skips SSTables that definitely do not contain the key, without any disk read. At about 10 bits per key, a 1 percent false-positive rate turns a lookup that might touch dozens of SSTables into one or two disk reads. The same structure solves our feed problem one level up.
7. Ranking the stack: a two-sided recommendation problem#
Filtering decides who may appear. Ranking decides who appears first, and that drives match rates far more than any infrastructure choice. This is a reciprocal recommendation problem: a good recommendation for A is someone A is likely to like and who is likely to like A back. Optimising only "A will swipe right" fills stacks with the most popular profiles, who are already overwhelmed and rarely reciprocate. The result is few matches and an unhealthy marketplace.
Two stages.
- Candidate generation (recall): the geo plus filter search returns a few hundred to a few thousand eligible candidates, unordered or roughly ordered (for example by recent activity).
- Ranking (precision): a model scores each candidate for the viewer, and the top 200 form the stack.
This is the same two-stage pattern as the approximate-index-then-re-rank idea in Deep Dive 2: a cheap broad step, then an expensive precise one on a small set (see the recommendation-system problem).
Signals that matter.
- Activity recency: showing people who have not opened the app in weeks wastes the viewer's likes, because they will never see them. Boost recently active users. This single signal has a big effect on match rates.
- Predicted mutual interest: P(A likes B) × P(B likes A), from models trained on swipe history. The features include both users' profiles, behaviour and similarity in past likes.
- Distance: closer is generally better within the allowed radius.
- Profile quality and completeness: photos, bio and verification.
- Exposure balance: cap how often a very popular profile is shown, and give new users an exploration boost, so the system learns about them and they get early matches. A good first week matters for retention.
Desirability scores, then and now. A historically well-known approach was an Elo-like rating: each swipe is treated as a "match" between two players, and being liked by highly rated people raises your rating more. Tinder has publicly said it once used an Elo-style score and later moved away from relying on it. Today's systems are generally described as learned models over many signals, and exact production details are not public. In an interview, propose the learned two-sided score and mention Elo as a simple baseline.
Embeddings and vector search. One modern approach learns an embedding per user (from profile content and swipe behaviour), so that users likely to like each other are close in vector space. Candidate generation becomes "nearest neighbours to my taste vector" (see Vector Databases and Similarity Search). It must be combined with hard filters (distance, age, gender), which is filtered vector search:
- Post-filtering: retrieve the top N nearest neighbours (N much larger than K) and then apply the filters. If the filters are restrictive (a 5-mile radius in a small town), you may end up with too few results, so N must grow and the work grows with it.
- Pre-filtering: apply the hard filters first, and search only within that subset. Here a restrictive geo filter is a good thing: the subset may be only a few thousand users, and exact brute-force similarity over a few thousand vectors takes about a millisecond. Pre-filtering is usually the better choice when the filtered set is small, and for a dating app it usually is.
- Engines differ in how they combine the two. pgvector leaves the choice to the PostgreSQL planner. Elasticsearch applies filters during its HNSW traversal. Purpose-built vector databases keep metadata indexes alongside the vector index.
- The right answer depends on the data. In an interview, say you would benchmark on real selectivity.
Hybrid scoring. The final rank can blend a learned score, activity recency and distance in an Elasticsearch function_score (for real-time refills) or in a model service called by the Feed Builder (for precomputed stacks). Keep the model server's latency budget small (around 20 ms for 500 candidates) on the real-time path. Precomputed stacks can afford heavier models.
Feedback loops. Ranking changes behaviour, and behaviour trains the ranker. Watch match rate, reply rate after a match and retention, not just swipe-right rate, which is easy to inflate. Run changes as A/B experiments, and watch both sides of the marketplace.
8. Match notifications: reliable, deduplicated and timely#
Durably record the match first, then notify. Use the outbox idea: the Swipe Service publishes MatchCreated to Kafka, keyed by match ID, as part of handling the swipe (see Change Data Capture and the Outbox Pattern). Consumers then:
- write the match to
matches_by_userfor both users (two rows, deterministic match ID, idempotent upserts); - create the conversation in the chat system;
- send the push notification to the first swiper (A), and an in-app event to B if B has another device open.
Push delivery. A's devices are registered with device tokens from APNs (iOS) and FCM (Android), stored per user and refreshed when the platform rotates them. The Notification Service:
- looks up A's tokens;
- builds a localised payload ("You have a new match!" plus the match ID);
- sends it through APNs or FCM over their HTTP/2 APIs.
It handles platform responses: it removes tokens reported invalid, and retries throttling and transient errors with back-off.
At-least-once plus deduplication. Kafka consumers may process an event twice after a crash. Deduplicate by match ID in a small store with a TTL, so A is not pushed twice. Pushes themselves are best-effort; the platforms do not guarantee delivery. The match is still visible in the app's match list the next time A opens it, so a lost push loses nothing permanent.
Realtime if online. If A has the app open, a push is a poor experience. Instead deliver an in-app event over an existing WebSocket or server-sent-events connection, so the "It's a match!" screen appears immediately (see Pattern: Pushing Realtime Updates). A presence service records which users have a live connection, and the Notification Service picks the channel.
Product rules. Respect quiet hours and notification settings. Batch multiple matches within a few minutes into one push ("You have 3 new matches"). Never leak who the match is on the lock screen if the user's privacy settings say not to.
Volume. 7 to 13 million matches per day is about 100 to 150 pushes per second on average, with evening peaks of a few hundred. That is easy for a small Notification Service fleet. APNs and FCM handle the fan-out to devices. See the notification-system problem for the general design.
9. Reconciliation: a safety net for lost matches#
Even with atomic pair checks, matches can be lost in rare cases:
- Redis loses recent writes in a failover (asynchronous replication).
- A Swipe Service instance crashes after the Redis script, but before publishing
MatchCreated. - A consumer bug drops events.
A missed match is a silent, user-visible failure, the exact thing the consistency requirement forbids. So add a reconciliation job as defence in depth.
How it works.
- A batch job (Spark over a Cassandra snapshot, or over swipe events landed in the data lake) runs periodically, for example hourly over the last day's likes, and weekly over everything.
- It finds pairs where A liked B and B liked A.
- It anti-joins with the match store to find pairs with no match.
- For each, it creates the match idempotently and notifies both users. Neither can tell the match was detected late; each assumes the other just swiped.
-- Mutual likes in the last day with no match (data-lake SQL)
SELECT LEAST(a.swiper_id, a.target_id) AS low, GREATEST(a.swiper_id, a.target_id) AS high
FROM likes a
JOIN likes b ON a.swiper_id = b.target_id AND a.target_id = b.swiper_id
LEFT JOIN matches m ON m.match_id = CONCAT(LEAST(a.swiper_id, a.target_id), ':', GREATEST(a.swiper_id, a.target_id))
WHERE a.created_at > now() - INTERVAL '1' DAY
AND a.swiper_id < a.target_id
AND m.match_id IS NULL;Handling the crash between script and publish. There are two ways to close this window:
- Publish first: append
SwipeRecordedto Kafka before running the Redis script, and have a consumer that, on a yes, re-checks the pair and creates the match if both sides are yes. The synchronous script still gives B the instant response, and the consumer catches anything the request path dropped. - Make the request path retry-safe: if the client retries the swipe after a timeout, the script runs again and returns the same result, because the decision is idempotent and the match ID is deterministic.
Monitor it. The number of matches the reconciler creates is a health metric. It should be close to zero. A spike means a Redis failover, a consumer outage or a bug, and it should page someone.
10. Sharding, hot spots and multi-region#
Per-store sharding.
| Store | Shard key | Why |
|---|---|---|
| Profile DB | user ID | Point reads and writes by user |
| Search index | evenly by document, or by region | Geo queries; balanced load |
| Swipe DB | swiper ID (with an optional time bucket) | History per swiper; even write spread |
| Pair state | sorted pair key | Atomic match check on one shard |
| Stack cache and seen filters | user ID | Per-user reads |
| Kafka swipes topic | swiper ID | Per-user ordering |
Hot spots.
- Popular profiles receive many likes, but each like is a different pair key, so the pair store spreads them. In
swipes_by_swiperthey are spread by swiper. Nothing is keyed by target on the write path, which is deliberate. A "likes received" listing for premium features would be a separate, asynchronously built table, bucketed by target and time. - Dense cities concentrate search load. Replicas of the search shards absorb read load. If the index is region-routed, split big metros into several geohash ranges.
- The evening peak is predictable. Pre-scale the Swipe Service and Feed Service, and warm stacks before the peak (Deep Dive 4).
Multi-region. Users are local: almost all swipes and matches are between people in the same region. So deploy per region, and give each user a home region, where their profile, swipes and stacks live.
- Requests are routed to the home region.
- Cross-region pairs are rare, but possible with a "travel" or "passport" feature, or near borders. Pair atomicity needs one owner per pair. Route the pair check deterministically, for example to the home region of the lower user ID, at the cost of a cross-region call for those rare swipes.
- Profile documents of users near borders can be indexed in both regions' search clusters.
- Region failover: profiles and swipes are replicated asynchronously to a standby region. During a failover, a few seconds of swipes may be missing, and the reconciler repairs any missed matches afterwards.
See Multi-Region and Global Data.
11. Location privacy, safety and trust#
These are below the line for the core design, but a strong candidate shows where they plug in.
Location privacy.
- Store only a coarse location for matching (rounded, or snapped to a cell).
- Return distance buckets only.
- Rate-limit location changes, so an attacker cannot "move" an account around to triangulate a target.
- Do not log raw coordinates longer than needed.
- Treat location as sensitive personal data under privacy law, with retention limits and user deletion.
Blocks and reports.
- A block must take effect instantly and in both directions. Neither person may appear in the other's stack, swipes between them are ignored, and any existing match and chat is closed.
- Implement this with a per-user block set checked at serve time and at build time, and with a pair-level flag that the Swipe Service checks before running the match script.
- Reports feed a trust and safety pipeline.
Fake profiles and bots. Use signals such as swipe cadence (hundreds of right swipes a minute), a 100 percent like ratio, many accounts per device, identical photos across accounts and message spam after matches. Actions:
- Shadow-limit: the account's swipes stop counting and it stops appearing in stacks, without telling it.
- Require photo verification.
- Ban the account.
These signals come from the swipe event stream, which we already have in Kafka.
Age and consent. Enforce a minimum age at sign-up. Never let a filter or a bug show adults to minors, or the other way round. Make age a hard filter in both directions, at index time and at serve time.
See Security Fundamentals for System Design.
12. Profiles, photos and card hydration#
Profile Service and data. The profiles themselves (name, birth date, bio, prompts, photo references, preferences and last coarse location) live in PostgreSQL, sharded by user ID once a single primary is no longer enough. Read replicas serve profile views. CDC streams changes to the search index and the profile cache.
Photos. Photos are the product's core content, but a standard blob problem (see Pattern: Handling Large Files and Blobs):
- The client uploads directly to object storage with a pre-signed URL.
- An async pipeline checks the content (moderation), generates several sizes (thumbnail, card and full screen) in modern formats, and records the URLs on the profile.
- Images are served from a CDN (see Content Delivery Networks (CDN)).
Hydration: from IDs to cards. Stacks hold IDs, not full profiles, for three reasons:
- IDs are tiny (32 GB for all stacks, versus many times that for full cards);
- profile edits are visible immediately, with nothing to rewrite inside stacks;
- the serve-time check needs the current profile anyway.
The Feed Service hydrates a batch of 50 IDs with a single multi-get to a profile cache (Redis or Memcached, keyed by user ID, invalidated on change through CDC). A multi-get takes about 1 to 3 ms. The card includes CDN photo URLs, so the client starts fetching the images right away.
Prefetching images. The client prefetches the photos for the next few cards while the user looks at the current one, so every swipe reveals a card that is already loaded. This matters more to the perceived speed than the 300 ms stack budget does.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Check-then-write on separate partitions | Simultaneous mutual likes produce no match | Pair key with atomic write-then-read (Redis Lua, LWT, or strict quorums); idempotent match IDs |
| Redis failover loses recent pair state | Missed matches for the last few seconds | Kafka as durable record, Cassandra fallback on missing key, reconciliation job, optional WAIT |
| Crash between pair check and MatchCreated | Match detected but never stored or notified | Publish swipe first and re-check in consumer; retries are idempotent; reconciler |
| Swipe write spikes at evening peak | Write latency, database pressure | Kafka buffer, LSM store, batched consumer writes, pre-scaling, client batching of passes |
| Naive lat/long range query | Stack takes seconds, database overloaded | Search engine with BKD geo index and filter caching; precomputed stacks |
| Heavy users exhaust cached stacks | Slow loads for the most engaged users | Refill at a threshold, real-time search fallback, larger stacks for heavy users |
| Stale cached stacks | Users see profiles that no longer fit, or banned or blocking users | Short TTL, viewer-side triggers, serve-time validation, instant deny sets |
| Huge swipe histories | Slow exclusion, repeats | Client recent-swipe cache, exact sets for light users, Bloom filters for heavy users |
| Bloom filter cache node lost | Repeats or expensive mass rebuild | Replicas and snapshots, lazy rebuild, exact fallback plus client cache meanwhile |
| Popular profiles flooded with likes | Hot keys, poor marketplace health | No target-keyed hot path; exposure caps in ranking; asynchronous likes-received table |
| Push provider throttling or invalid tokens | Delayed or lost match notifications | Retry with back-off, remove invalid tokens, in-app match list as source of truth |
| Precise distances exposed | Stalking through trilateration | Coarse stored location, distance buckets, rate limits on location changes |
What Interviewers Expect#
Mid-level:
- Defines clear APIs (profile, feed, swipe), with identity taken from the auth token.
- Gives a sensible data model and a working high-level design covering stack generation, swiping and matching.
- Handles both traditional and geospatial filters, for example with a search engine or a geo index instead of lat/long ranges.
- Proposes a way to avoid re-showing swiped profiles.
- Is not expected to know deep internals of specific technologies.
Senior:
- Moves quickly through the basics and spends time on efficient, scalable stack generation and reliable match creation.
- Proactively compares real-time indexed search with precomputed stacks and lands on the hybrid.
- Knows what kind of index powers geo plus filter queries.
- Explains when cached stacks go stale and how to contain it.
- Identifies the mutual-swipe race and fixes it with a pair-keyed atomic operation.
- Justifies a write-optimised store for swipes, with a sensible partition key.
Staff+:
- Goes deep on every topic above, and may steer towards whatever is most interesting.
- Proves why write-then-read on a linearizable pair record cannot miss a match, and why both sides may see it (hence idempotent matches).
- Weighs Redis against LWT against quorum trade-offs, including durability on failover, and adds reconciliation as a safety net.
- Sizes Bloom filters and explains what false positives mean for the product.
- Treats the stack as a tunable system (TTL, size, warm set, refill threshold).
- Frames ranking as reciprocal recommendation.
- Covers privacy (trilateration), blocks and abuse.
- Discusses the interviewer's trade-offs as a peer.
Deep Dive: Cassandra internals that matter for the swipe storeShow
Write path.
- A coordinator node receives the write and forwards it to the replicas that own the partition: with replication factor 3, three nodes chosen by the token ring (see Consistent Hashing).
- Each replica appends the write to its commit log for durability, and inserts it into the memtable for that table.
- When enough replicas have acknowledged to satisfy the consistency level (1 for
ONE, 2 forQUORUMwith RF 3), the coordinator replies. - Memtables flush to immutable SSTables when full. Compaction merges SSTables in the background, discarding overwritten values and expired tombstones.
Because nothing is updated in place, a swipe costs a sequential append plus an in-memory insert on each replica. That is why a modest cluster absorbs 100,000+ writes per second.
Read path for "did A swipe on B?".
- The coordinator asks enough replicas for the consistency level.
- Each replica checks the memtable, then, for every SSTable, consults its Bloom filter. If it says "definitely not here", the SSTable is skipped with no disk I/O. If it says "maybe", the replica uses the partition index and summary to seek directly to the row.
- The coordinator merges the versions by timestamp (last write wins), and may trigger read repair if replicas disagree.
With per-swiper partitions and levelled compaction, most point reads touch one or two SSTables.
Consistency levels and the race.
ONEwrites andONEreads are fastest, but a read can miss a write that went to other replicas. For match detection this is exactly the failure we must avoid.QUORUMwrites and reads (R + W = 4 > N = 3) guarantee that a read starting after a write completed sees it. As shown in Deep Dive 1, that is enough for write-then-read match detection.LOCAL_QUORUMkeeps that guarantee within one data centre without cross-region latency. Use it when each pair's check is owned by one region.
Lightweight transactions under the hood. An LWT runs a Paxos round among the partition's replicas:
- Prepare / promise: the coordinator proposes a ballot, and a quorum promises not to accept older ballots.
- Read: it reads the current value to evaluate the
IFcondition. - Propose / accept: it proposes the new value, and a quorum accepts.
- Commit: it makes the value visible.
That is about four round trips between replicas, compared with one for a normal write, so LWT latency is commonly several times higher. Under contention on the same partition, ballots can conflict and retry. For a pair that only two people ever write to, contention is negligible, so the cost is purely latency. Newer Cassandra releases have introduced improved consensus-based transaction protocols. Check what your version supports rather than assuming.
Tombstones and TTLs. Deleting or expiring a row writes a tombstone, which must survive for gc_grace_seconds (10 days by default) so that every replica learns of the deletion before it is purged. A partition with many tombstones makes reads scan them, and Cassandra warns or aborts past configurable thresholds. For swipe TTLs, this argues for:
- consistent TTLs per table;
- compaction that groups data by age;
- avoiding patterns that delete and re-insert the same rows repeatedly.
Hinted handoff and repair. If a replica is down during a write, the coordinator stores a hint and replays it when the replica returns. Hints are kept only for a limited window. Beyond that, scheduled anti-entropy repair (Merkle-tree comparison between replicas) restores consistency. Run repair regularly within gc_grace_seconds. Otherwise deleted swipes can resurrect when an out-of-date replica later shares stale data.
Deep Dive: Redis Cluster for the pair store, slots, resharding and memoryShow
Slots. Redis Cluster splits the key space into 16,384 hash slots. A key's slot is CRC16(key) mod 16,384, and each primary owns a range of slots. If a key contains a hash tag in braces, {...}, only the tag is hashed. That lets several related keys share a slot, which multi-key scripts require. Our match script touches one key, so hash tags are not needed. If we later added a second key per pair (for example a per-pair lock or a block flag), we would tag both with the pair, as in swipes:{12:45} and block:{12:45}, so the script can touch both atomically.
Resharding and scripts. When slots move between nodes (to add capacity), keys migrate one by one. A client that hits a key that has already moved gets a MOVED or ASK redirect and retries on the new owner. Cluster-aware client libraries handle this. A script on a key that is mid-migration gets redirected too, so atomicity is preserved per key. Plan resharding for off-peak hours, because migrations add latency.
Failover semantics.
- Each primary has one or more replicas. If a primary fails, the cluster promotes a replica after a timeout of seconds.
- Replication is asynchronous: the primary acknowledges before replicas confirm. Writes in the last moments can vanish on promotion.
WAIT numreplicas timeoutblocks until that many replicas have acknowledged the preceding writes. It reduces the loss window, but it is not a consensus guarantee: a replica that acknowledged may itself not be the one promoted.
That is why the design treats Redis as the fast path and Kafka plus Cassandra as the record.
Memory sizing in detail. Small hashes are stored in a compact encoding (listpack) as long as they stay under configurable size thresholds. A pair hash with one or two short fields fits easily, so it costs roughly the key string (about 25 bytes) plus encoding and per-key overhead, plus the expiry entry. That comes to something like 70 to 120 bytes per pair in practice; measure it with MEMORY USAGE on real keys.
- At 670 million new yes-swipes per day and a 7-day TTL: 4.7 billion pairs × about 100 B ≈ 470 GB. With one replica each, about 940 GB of RAM.
- That is around 16 to 20 primaries of 32 to 64 GB, each paired with a replica.
- Halving the TTL halves the memory. The cost is more Cassandra fallbacks for likes older than 3.5 days, which are cheap single-partition reads.
Throughput. The match script is a few microseconds of Redis CPU. A single shard comfortably runs tens of thousands of such scripts per second. At a peak of about 25,000 to 50,000 yes-swipes per second (a third of all swipes), spread over 16 or more shards, each shard runs only a few thousand per second, so the cluster is sized by memory, not CPU.
Alternatives if Redis memory is too costly. Use Cassandra pair rows with strict quorums (no RAM cost, a few milliseconds per swipe), or DynamoDB pair items with conditional updates (pay per request, no cluster to run). The algorithm is identical; only the latency and cost profile change.
Deep Dive: Geo index maths for the stack queryShow
Geohash cells for a radius. A geohash with p characters encodes 5p bits, alternating longitude and latitude. Approximate cell sizes at mid-latitudes:
| Geohash length | Cell size (approximate) |
|---|---|
| 4 | ~39 km × 20 km |
| 5 | ~4.9 km × 4.9 km |
| 6 | ~1.2 km × 0.6 km |
For a 10-mile (16 km) radius, length-5 cells are a sensible grain. The circle's bounding box is 32 km across, which spans about 7 × 7 = 49 length-5 cells. Alternatively, use a coarser length-4 cell plus its 8 neighbours (9 cells), and then exact-distance filter. The trade-off is between the number of range scans and the number of false candidates to discard. Most engines choose the covering automatically.
What Elasticsearch actually does. geo_point fields are indexed in a BKD tree, which recursively splits points by latitude and longitude into blocks on disk. A geo_distance query walks the tree:
- Blocks entirely inside the circle are accepted wholesale.
- Blocks entirely outside are skipped.
- Only blocks on the boundary have their points checked one by one.
Combined with filter caching of common clauses, this makes a 10-mile query over a dense city fast, even with millions of documents in the shard.
How many candidates? Suppose 2 percent of a metro's 10 million people are active users of the app: 200,000 users. A 10-mile radius in a dense city might contain half of them, about 100,000. Gender and interest filters cut that to about 40,000. An age range of 10 years leaves about 10,000. Reciprocal filters leave about 6,000. Excluding the seen ones leaves a few thousand.
The query is therefore selecting thousands from millions. Ranking then picks 200. In a rural area, the same filters might leave only 50 candidates in total. Then the product decision is whether to expand the radius automatically (with the user's consent setting) or to show "you've seen everyone nearby".
Distance computation. Use the haversine formula for exact distances. For bucketed display, an equirectangular approximation is accurate to well under 1 percent at these ranges, and cheaper. Always compute distance from the coarsened stored locations, so the bucket is consistent with what the server knows.
Redis GEO as an alternative. For a lighter stack, GEOADD and GEOSEARCH ... BYRADIUS store members in a sorted set scored by a 52-bit geohash. Radius search then becomes a few score-range scans plus distance filtering. This works well for "who is nearby", but it has no secondary filters. You would need one set per (region, gender, interested-in) segment, and age filtering afterwards. It is fine for prototypes; the search engine wins once filters multiply.
Deep Dive: Capacity plan per tierShow
These are illustrative sizes for the 20 million DAU target, peak of about 100,000 swipes per second. Real numbers come from load tests (see Capacity Planning and Load Testing).
| Tier | Load at peak | Per-unit capacity (assumed) | Units, with headroom |
|---|---|---|---|
| Swipe Service | 100k req/s | ~5k req/s per instance (I/O bound: Redis + Kafka) | ~30 to 40 instances |
| Kafka swipes topic | 100k msg/s, ~10 MB/s | Easily handled by a small cluster | 6 to 9 brokers, ~100 partitions |
| Cassandra swipe store | 100k writes/s × RF 3 | ~15k to 30k writes/s per node | ~20 to 30 nodes |
| Redis pair store | ~35k scripts/s; ~500 GB | Memory-bound | ~16 to 20 primaries plus replicas |
| Feed Service | ~4k req/s | ~1k to 2k req/s per instance | ~6 to 10 instances |
| Elasticsearch | ~4k real-time queries/s plus warm-ups; 100 GB | ~200 to 500 filtered geo queries/s per data node | ~15 to 30 data nodes with replicas |
| Redis stacks and seen filters | ~32 GB stacks plus ~240 GB filters | Memory-bound | ~8 to 10 primaries plus replicas |
| Notification Service | ~300 pushes/s at peak | Trivial | 3 to 4 instances |
Storage growth. Cassandra grows by about 200 GB per day before replication. With 1-year retention for passes and 3 years for likes, steady state is around 100 TB raw, or 300 TB replicated. At about 2 to 4 TB per node, that is on the order of 100 nodes for storage. So the swipe cluster is eventually sized by disk, not writes. The TTL policy on passes is the biggest cost lever in the whole system.
Cost intuition. The dominant costs are the swipe store's disks, the RAM of the Redis pair store and the search cluster. Shortening pass retention, shortening the pair-state TTL, and precomputing stacks only for genuinely active users are the three knobs with the largest effect.
Deep Dive: Cold start and the new-user experienceShow
A new user has no swipe history, so the ranker knows nothing about their taste, and nobody knows how others respond to their profile. Yet the first sessions decide whether they stay.
For the new user's own stack. Start with a popularity-and-activity prior: recently active profiles with good reciprocity in the area. Then learn fast from the first 20 to 50 swipes, and update their taste embedding or features after each session, not only in nightly batches.
For showing the new user to others. This is an exploration problem. If the ranker only shows profiles with proven high scores, new profiles are never shown, so they never get data, so they are never shown. This is the classic explore/exploit dilemma, and multi-armed bandit methods address it.
- Give each new profile a time-limited exposure boost.
- Track its like rate with a Bayesian estimate (for example a Beta distribution over the like probability).
- Use Thompson sampling (sample from the distribution, rank by the sample) or an upper-confidence-bound score. Profiles with uncertain estimates then get shown enough to resolve the uncertainty.
Guardrails.
- Cap the boost so new users do not crowd out everyone else.
- Show new users preferentially to active people, so their early likes are seen.
- Measure time to first match as the north-star metric for onboarding.
Infrastructure impact. None of this changes the architecture. It changes the ranking step and adds a few per-profile counters (impressions, likes received) maintained from the event stream, with the batched or milestone write techniques from Deep Dive 2.
Deep Dive: Marketplace dynamics the system must respectShow
A dating app is a two-sided marketplace, and several engineering decisions are really market-design decisions.
Attention is the scarce resource. Every profile shown is a slot in someone's limited session. Showing a very popular profile to everyone concentrates likes on a few people. They cannot respond to all of them, so most likes are wasted, and the rest of the market sees few matches. Exposure caps in ranking spread attention, and they usually raise total matches, even though each viewer's individual swipe-right rate may fall.
Imbalanced sides. In many markets, one side of the market likes far more often than the other. If unchecked, one side faces an overwhelming inbound volume and the other side very few matches. Product levers include daily like caps for free users (which ration attention and make each like more meaningful), and ranking that favours people likely to reciprocate. Some products also change who can message first. Each lever changes swipe volume, and therefore the write load, so capacity plans must follow product changes.
Selectivity signals. A user who likes everyone gives no information, and their likes are worth little to recipients. Ranking models therefore weight a like by the liker's selectivity. This is another reason bots and indiscriminate swipers should be detected and down-weighted early.
Location density. In dense cities, the problem is choosing among too many candidates, so ranking matters most. In sparse areas, it is finding enough candidates at all, so radius expansion and relaxed soft filters matter most. A single global configuration serves neither well. The tunable stack parameters (Deep Dive 4) should be set per market.
Measuring success. Swipe counts are a vanity metric. Matches, conversations started, conversations with replies, and retention on both sides measure whether the system is working. Infrastructure choices such as stack freshness, repeat avoidance and match reliability show up in these numbers. That is the bridge between the systems design and the business.
Experiments. Every ranking or market lever above should ship behind an A/B test with guardrail metrics for both sides, because a change that helps one side can quietly hurt the other. Randomise by user, and watch for interference: in a marketplace, treated and control users swipe on each other, so effects leak across groups.
Deep Dive: The client, local queue, prefetch and perceived speedShow
Much of what makes swiping feel instant happens on the phone, not the server.
Optimistic swipes. When the user swipes, the card animates away immediately. The swipe is written to a local queue (for example SQLite on the device) with its idempotency key, and sent in the background. The UI never waits for the server, except for a match result. If the response says matched: true, the client shows the match screen a few hundred milliseconds later, which users perceive as part of the animation.
Offline and flaky networks.
- Queued swipes survive app restarts, because they are on disk.
- On reconnect, the client flushes them in order, in batches.
- Because each swipe carries a stable idempotency key, retries after timeouts cannot double-count.
- Server-side, a swipe arriving hours late is still valid. Its timestamp is the client's swipe time, bounded by server sanity checks so a manipulated clock cannot backdate it far.
Stack buffering. The client holds the next 20 to 50 profiles and requests more when about 10 remain. It never runs dry during a fast session, and each fetch is a single cheap read of the precomputed stack. Locally, it also removes any profile the user has already swiped in this session, even if the server's next page includes it because the swipe had not yet been processed. This is the client-side half of repeat avoidance.
Image prefetch. Photos dominate bandwidth. A profile with 4 to 6 images at about 100 to 200 KB each is roughly 1 MB.
- Prefetch the first photo of the next 5 to 10 cards, and the remaining photos only for the next 1 or 2.
- Request sizes matching the screen density, using the resized variants the CDN serves (see Content Delivery Networks (CDN)).
- On metered or slow connections, prefetch less and use lower quality.
The result: the card is already rendered when it slides in, while data use stays bounded.
Battery and location. Request coarse location only when the app is in the foreground, and only on meaningful movement (for example more than 1 km, or at session start). Continuous high-accuracy GPS drains batteries and adds nothing, because the server coarsens location anyway.
Client-side rate signals. The client knows the swipe rhythm: a human swipes perhaps one card per second or two, with pauses to view photos. A bot swipes metronomically without loading images. The client can attach coarse behavioural signals (time on card, photos viewed) that the server's anti-abuse model uses. Treat them as hints, never trust them alone, because a modified client can forge them.
Versioning and kill switches. Old app versions stay in the wild for years. The API must keep accepting older payloads, and the server should be able to switch features off remotely (for example disabling a new swipe type) without a release. Feature flags fetched at startup handle this.
Why this matters for the backend.
- Batching and queuing on the client smooth traffic spikes.
- Prefetching shifts load to the CDN.
- Client-side deduplication masks the few seconds of eventual consistency in the seen filter.
A good client design makes the server's job measurably easier, and interviewers reward candidates who notice that.
Deep Dive: The Swipe Service handler in TypeScriptShow
const SCRIPT = `
redis.call('HSET', KEYS[1], ARGV[1], ARGV[2])
redis.call('EXPIRE', KEYS[1], ARGV[4])
return redis.call('HGET', KEYS[1], ARGV[3])`;
async function handleSwipe(me: bigint, target: bigint, decision: "yes" | "no") {
if (await blocks.eitherBlocked(me, target)) return { match: null }; // safety first
const [low, high] = me < target ? [me, target] : [target, me];
const event = { swiper: me, target, decision, at: Date.now() };
await kafka.send("swipes", String(me), event); // durable record first
if (decision === "no") return { match: null }; // passes never match
const key = `swipes:${low}:${high}`;
let other = await redis.eval(SCRIPT, [key], [String(me), "yes", String(target), String(7 * 86400)]);
if (other === null) {
// pair key absent or expired: our yes is now in Redis; check durable history
other = (await cassandra.getDecision(target, me)) ?? null; // swipes_by_swiper(target, me)
}
if (other !== "yes") return { match: null };
const matchId = `${low}:${high}`; // deterministic, idempotent
await kafka.send("matches", matchId, { matchId, users: [low, high], at: Date.now() });
return { match: { matchId, userId: target } };
}Four details carry the correctness:
- The block check runs first.
- The Kafka write before the script means a crash after the script cannot lose the swipe; a consumer re-checks pairs on yes events.
- The Cassandra fallback handles expired pair state.
- The deterministic match ID makes double detection harmless.
Deep Dive: Bloom filter implementation and false-positive mathsShow
// Bloom filter with double hashing: h_i(x) = h1(x) + i * h2(x) mod m
class Bloom {
bits: Uint8Array; m: number; k: number;
constructor(n: number, p: number) {
this.m = Math.ceil((-n * Math.log(p)) / Math.LN2 ** 2);
this.k = Math.max(1, Math.round((this.m / n) * Math.LN2));
this.bits = new Uint8Array(Math.ceil(this.m / 8));
}
private idx(id: string): number[] {
const h1 = fnv1a(id), h2 = (murmur32(id) | 1) >>> 0; // odd step
return Array.from({ length: this.k }, (_, i) => (h1 + i * h2) % this.m);
}
add(id: string) { for (const b of this.idx(id)) this.bits[b >> 3] |= 1 << (b & 7); }
mightContain(id: string) { return this.idx(id).every(b => (this.bits[b >> 3] >> (b & 7)) & 1); }
}Where the formula comes from. After inserting n items with k hashes into m bits, the chance a given bit is still 0 is (1 − 1/m)^(kn), which is approximately e^(−kn/m). A false positive needs all k probed bits to be 1, so p ≈ (1 − e^(−kn/m))^k. Minimising over k gives k = (m/n) ln 2, at which point each bit is 1 with probability 1/2, and p = (1/2)^k. Solving for m gives m/n = −ln p / (ln 2)², about 1.44 log₂(1/p) bits per item.
Worked example. A user has 40,000 swipes, and we want p = 0.5 percent.
- m/n = −ln(0.005) / 0.4805 ≈ 11.0 bits per item, so m ≈ 441,000 bits, about 55 KB.
- k = 11.0 × 0.693 ≈ 7.6, so use 8 hashes.
- If the user doubles their history to 80,000 swipes without resizing, the load kn/m doubles. Then p ≈ (1 − e^(−8 × 80,000 / 441,000))^8 ≈ (1 − e^(−1.45))^8 ≈ 0.765^8 ≈ 12 percent. That is far too high, which is why the filter must grow (scalable filters) or be rebuilt when it passes its design capacity.
Double hashing. Kirsch and Mitzenmacher ("Less Hashing, Same Performance: Building a Better Bloom Filter", 2006) showed that deriving all k indices from two base hashes as h1 + i·h2 keeps the same asymptotic false-positive rate. That makes k hashes nearly as cheap as two.
Deep Dive: Why the naive check misses matches, and the exact fix, step by stepShow
Label the operations. A runs C_A (check whether B liked A), then W_A (write that A likes B). B runs C_B, then W_B.
Naive order (check, then write). The interleaving C_A, C_B, W_A, W_B is legal. Both checks run before either write, so both see nothing, and the match is lost. Nothing prevents it, because the check and the write are separate operations, possibly on separate partitions.
Write, then check, on separate partitions with weak consistency. Even with W before C, eventual consistency lets a check read a stale replica that has not yet received the other's write. Both checks can still see nothing.
Write, then check, on one linearizable record (or strict quorums). As proven in Deep Dive 1, at least one check must observe the other's write. Both may observe it, so match creation must be idempotent.
An atomic script (Redis). The write and the check become a single atomic operation per request, so the two requests are totally ordered. The second always sees the first. Exactly one request detects the match, unless a retry repeats the script, which is again harmless with a deterministic match ID.
| Approach | Can miss a match? | Can double-detect? | Cost |
|---|---|---|---|
| Check then write, separate partitions | Yes | No | Cheap |
| Write then check, eventual consistency | Yes | Yes | Cheap |
| Write then check, strict quorum or LWT on the pair | No | Yes (idempotent) | Moderate |
| Atomic script on the pair key | No (barring data loss on failover) | Only on retry (idempotent) | Cheapest per op |
| Any of the above plus reconciler | Detected late at worst | Idempotent | Batch cost |
Deep Dive: Latency budget for opening the appShow
| Step | Cached path | Real-time path |
|---|---|---|
| Mobile network round trip | 50 to 100 ms | 50 to 100 ms |
| Gateway and auth | 2 to 5 ms | 2 to 5 ms |
| Read stack and metadata from Redis | 1 to 2 ms | 1 ms (miss) |
| Search query (geo, filters, exclusions) | none | 30 to 120 ms |
| Seen filter checks on about 300 candidates | under 1 ms | under 1 ms |
| Ranking | none (precomputed) | 10 to 30 ms |
| Serve-time check and hydration via multi-get | 2 to 5 ms | 2 to 5 ms |
| Serialisation | 1 to 2 ms | 1 to 2 ms |
| Server total | ~10 ms | ~50 to 160 ms |
| User-perceived (with network) | ~60 to 110 ms | ~110 to 260 ms |
Both paths meet the 300 ms target. The cached path leaves a large margin for poor networks. Photos for the first card should be in flight within the same window. The client can also show the last cards it held from the previous session immediately, after re-validating them.
Deep Dive: Failure walkthroughsShow
1. A Redis shard of the pair store fails over.
- The replica is promoted within seconds. Writes acknowledged by the old primary in its last moments may be missing.
- Swipes in that window are still in Kafka. Consumers re-check yes swipes against the pair state (and Cassandra), and create any match that was missed.
- The reconciler's next run catches anything left. Users see, at worst, a match a few minutes late.
2. Elasticsearch is degraded.
- Real-time searches slow down or fail. Cached stacks keep serving.
- Refills fall back to an extended cached stack (build larger stacks during degradation), or to a simpler query: geo and the basic filters only, no ranking.
- The Feed Builder pauses non-urgent warm-ups to free capacity for refills.
3. Cassandra write latency spikes.
- Swipe consumers fall behind, and Kafka lag grows. Users notice nothing, because the request path only needs Redis and Kafka.
- Seen-filter updates also lag. The client's recent-swipe cache covers this window.
- Alert on consumer lag. Scale consumers out, or reduce batch sizes if the cause is timeouts.
4. A push provider outage.
- Notifications queue and are retried with back-off.
- Matches are already stored, so users who open the app see them in their match list.
- After recovery, collapse the queued notifications per user ("You have 4 new matches"), rather than sending a burst.
5. A bug shows profiles outside age filters.
- This is a safety incident.
- The serve-time check acts as a second, independent enforcement of hard filters (age, blocks, status). It should catch it, as long as the bug is in the builder rather than in both places.
- Roll back the builder, and invalidate all stacks built since the bad deploy, using
built_atand the builder version stored in the stack metadata.
Deep Dive: ObservabilityShow
Product health.
- Match rate per like.
- Time to first match for new users.
- Stack exhaustion events per session.
- Serve-time drop rate (a staleness indicator).
- Repeat-shown rate, measured from client reports of cards already swiped.
Correctness.
- Matches created by the reconciler (should be close to zero).
- Duplicate match attempts (expected, harmless).
- Pair-key misses that fall back to Cassandra (rises as TTLs are tuned down).
Latency.
- Feed p50 and p99, split by cached and real-time path.
- Swipe acknowledgement p99.
- Search query p99.
Pipelines.
- Kafka consumer lag per topic.
- CDC lag from the Profile DB to the index.
- Seen-filter update lag.
- Feed Builder queue depth.
Resources.
- Redis memory per shard (pair store, stacks, filters).
- Bloom filter fill ratios: alert if any filter exceeds its design capacity.
- Cassandra partition size outliers.
Slice by region and by app version: a client release that breaks the recent-swipe cache shows up as a rise in repeats on that version only. See Observability: Logs, Metrics and Traces.
Deep Dive: A 45-minute interview planShow
- Minutes 0 to 5: requirements. Profile with preferences, stack, swipe and match. Non-functional: consistent matching, 20M DAU × 100 swipes, a stack in under 300 ms, no repeats.
- Minutes 5 to 8: entities (User, Swipe, Match), APIs, and identity from the token.
- Minutes 8 to 18: the high-level design, per requirement. Profile Service with PostgreSQL. A naive feed query, and why it fails. A separate Swipe Service with Cassandra, and why. Match notifications through APNs and FCM.
- Minutes 18 to 28: consistent matching. The race, polling, transactions and LWT limits, then the pair key, and finally Redis Lua plus Cassandra. Mention reconciliation.
- Minutes 28 to 38: stack latency. Indexed search versus precompute, then the hybrid with refill. Staleness and its triggers. Geo index internals if asked.
- Minutes 38 to 45: repeats (client cache, then a Bloom filter with sizing), then wrap up with failure modes, ranking or privacy, whichever the interviewer prefers.
Deep Dive: Variants and how the design changesShow
- "Likes you" lists (premium): this needs a target-keyed view of incoming likes, which the core design deliberately avoids on the hot path. Build
likes_received_by_target, bucketed by time, asynchronously from the swipe stream. Exclude passes, and remove entries when the viewer swipes on the liker. - Rewind (undo the last swipe): keep the last swipe per user in a small store. Undo deletes the Kafka-propagated record, removes the ID from the exact seen set, and clears the pair-state field. A Bloom filter cannot delete, so keep the last few swipes out of the Bloom filter until they are final, and rely on the client cache and an exact recent set for them.
- Women message first (Bumble-style): this does not change matching, only chat permissions and expiry timers after a match.
- Likes on specific content (Hinge-style prompts): a swipe carries a reference to the photo or prompt liked. The data model gains a field, and notifications become richer.
- Friend-finding or networking modes: the same machinery with different filters and reciprocal rules, and often a separate index per mode.
- Group events and speed dating: time-boxed matching among a fixed set of attendees. Stacks are tiny and exact, so precomputation and Bloom filters are unnecessary.
Key Takeaways#
- Two very different paths: the feed is a read-latency problem with complex filters, and swiping is a write-volume and concurrency problem. Use separate services and stores for each.
- Geo plus filters belongs in a search engine with a spatial index (BKD
geo_pointin Elasticsearch), not in lat/long range scans. Include reciprocal preferences, and never expose exact locations. - Precompute stacks for likely-active users, and refill in real time before the stack runs out. TTL, size, warm set and refill threshold are tunable knobs. Contain staleness with triggers and serve-time validation.
- Swipes are about 2 to 4 billion writes per day: use an LSM store such as Cassandra partitioned by swiper, Kafka as the buffer and durable record, batched consumers and TTLs for passes. Use milestone or batched updates for derived counts.
- Mutual matches need per-pair atomicity: key by the sorted pair and write-then-read atomically (Redis Lua, LWT or strict quorums). Make match creation idempotent, and back it with a reconciliation job.
- Avoid repeats in layers: a client cache of recent swipes covers replication lag, exact sets cover light users, and Bloom filters cover heavy histories. Their false positives hide a few candidates but never re-show anyone. Size them at about 10 bits per item for 1 percent.
- Notifications: an event-driven outbox, idempotent by match ID, through APNs and FCM or in-app realtime. The match list is the source of truth.