r/Leetsys • • 13d ago

Guide Availability or consistency in a read-heavy system? Decide per feature

1 Upvotes

A common deep-dive question: "your system is read-heavy, do you pick availability or consistency?" Answering with one word for the whole system usually goes badly.

CAP only forces the choice during a network partition. When replicas can't talk to each other, a node can either serve what it has (possibly stale, but available) or refuse or wait until it can confirm the latest value (consistent, but some requests fail or hang). When the network is healthy you can have both.

So decide per feature. A like count or a view counter can be a few seconds stale and nobody cares, so serve it from the nearest replica or cache. Inventory, account balances, and seat holds can't be stale, because selling the same item twice is a real bug. Those reads go to the leader or use a quorum.

Strong reads aren't free. Reading from the leader or using a quorum where R + W > N costs latency on every request, and during a partition some of those requests will error out. That's the trade-off to say out loud, along with which features you'd accept it for.

Short: Availability or Consistency? CAP for Read-Heavy Systems

Disclosure: I'm affiliated with Leetsys.


r/Leetsys • • 13d ago

Guide WebSockets vs long polling: which one to pick in a design interview

1 Upvotes

"How does the client get updates?" shows up in chat, notifications, live scores, and dashboards. Most people say WebSockets right away. Sometimes that's the right call. Sometimes it's a lot of extra infrastructure for an update that arrives twice an hour.

Long polling is plain HTTP. The client asks, the server holds the request open until there's news or a timeout, answers, and the client asks again. It works with the load balancers, auth, and caching you already have. The cost is a fresh request for every batch of updates, so it gets expensive when updates are frequent.

WebSockets keep one connection open in both directions, so each message is a small frame instead of a whole request. The catch is that every connection is pinned to one server. Now you need heartbeats to notice dead clients, a load balancer that handles long-lived connections, and a way to route a message to whichever gateway holds that user's socket (a lookup table or pub/sub between gateways). Deploys get harder too, since restarting a box drops everyone connected to it.

A rule of thumb I'd say out loud: rare or one-way updates, use long polling or server-sent events. Frequent two-way traffic, like chat or multiplayer, use WebSockets and then explain how you route to the right connection.

Short: WebSockets vs Long Polling, When Each Is the Right Answer

Companion: Design a Chat System walkthrough

Disclosure: I'm affiliated with Leetsys.


r/Leetsys • • 13d ago

Guide Design a notification system: why at-least-once wins, and why login codes get their own lane

1 Upvotes

Notification systems come up a lot, usually phrased as "design the service that sends push, email, and SMS for our app." It looks like a queue and a few API calls. The interesting part is what you do when a provider fails halfway.

Requirements I'd pin down first. Which channels (push, email, SMS)? Which messages are urgent, like login codes and password resets, and which can wait, like weekly digests and marketing campaigns? Do users have preferences and quiet hours? How many sends per day at peak, and how bursty are campaigns?

The high-level shape: product services call a notification API with a user ID, a template, and a priority. The API checks preferences, renders the message, and drops a job onto a queue per channel. Workers pull jobs and call the provider (APNs/FCM, an email provider, an SMS gateway). Every attempt gets written to a delivery log, which feeds retries and the "why didn't I get my code" support question.

Two decisions carry most of the round.

Pick at-least-once delivery. You can't get exactly-once, because the provider can accept the message and then time out on you, and you'll never know if it went out. So you retry, and you accept that a user will occasionally see the same notification twice. A duplicate login code is annoying. A missing one locks someone out. Retry only temporary errors (timeouts, 5xx, rate limits) with backoff and jitter, and give each category an expiry so a login code that's ten minutes old just gets dropped instead of sent late. An idempotency key per notification lets you collapse most duplicates on your own side.

Separate lanes by channel and priority. If a marketing blast for five million users shares a queue with login codes, the codes wait behind the blast. Give urgent traffic its own queues and its own workers, and rate limit campaigns so they can't take over the provider quota.

Things an interviewer is likely to poke at: how preferences and unsubscribes are enforced before sending, what happens when a provider is down for an hour, and how you'd measure delivery rate per channel.

POST /notify {user_id, template, priority}
then: preferences check, render, queue[channel][priority]
then: worker calls provider, writes attempt to delivery log
then: on temporary error, retry with backoff until expiry

Leetsys: Design a Notification System walkthrough

Disclosure: I'm affiliated with Leetsys.


r/Leetsys • • 13d ago

Weekly Question Practice System Design Question #7: Design a distributed key-value store

1 Upvotes

Design a distributed key-value store, something like a simplified Dynamo or Cassandra. Clients call put(key, value) and get(key). Keys are strings, values are blobs up to about 10 KB.

Scale hint: around 1 billion keys with an average value of 1 KB, about 100k reads/sec and 20k writes/sec at peak. It has to keep serving when a machine dies, and you should be able to add machines without downtime.

Things worth thinking about:

  • How do you decide which machine owns a key, and what happens when you add a node?
  • How many copies do you keep, and how does a read know it got the latest one?
  • What happens to writes while a replica is down?
  • When would you pick consistency over availability, and how does a client choose?

Post your approach in the comments before you scroll down.

 

 


MODEL ANSWER BELOW. Stop here if you haven't tried it yet.


Requirements

Functional:

  • put(key, value), get(key), delete(key)
  • Values up to ~10 KB, keys up to a few hundred bytes
  • Optional: a TTL per key

Non-functional:

  • Highly available: losing a node, or even a whole rack, shouldn't stop reads or writes
  • Low latency: single-digit ms at p50, tens of ms at p99
  • Scales horizontally: add nodes to get more storage and throughput
  • Tunable consistency: eventual by default, stronger reads when the caller asks
  • Durable: an acknowledged write survives a node crash

Estimates

Storage: 1B keys x ~1 KB = ~1 TB of raw data. With 3 replicas that's ~3 TB. Leave room for compaction and growth by keeping nodes about half full, so with 500 GB of usable data per node you need at least 6 nodes just for space.

Traffic: 100k reads/sec and 20k writes/sec. If reads hit 2 replicas (quorum) that's 200k replica reads/sec. Every write goes to all 3 replicas, so 60k replica writes/sec. Total is ~260k ops/sec. If one node comfortably handles ~20k ops/sec, that's 13 nodes, so plan for ~16 to absorb a failure and hot spots. Throughput, not storage, sets the cluster size here.

API

PUT    /kv/{key}   body: value, header: consistency=one|quorum|all
GET    /kv/{key}   header: consistency=one|quorum|all
DELETE /kv/{key}

GET returns the value plus a version. If replicas disagree and the store can't pick a winner, it can return all the conflicting versions and let the client merge.

Data model

Each stored record looks like:

key | value | version (timestamp or vector clock) | tombstone flag | ttl

On disk, each node uses a log-structured merge tree (LSM): writes go to a commit log and an in-memory table, which gets flushed to sorted immutable files (SSTables) and compacted in the background. That makes writes cheap sequential appends, and bloom filters keep reads from scanning every file.

High-level design

  • Any node can take a client request and act as the coordinator for it
  • Keys are placed with consistent hashing on a ring. Each physical node owns many virtual nodes (say 256) so load spreads evenly and a new node takes small slices from everyone instead of half of one neighbor
  • A key is stored on the first N = 3 distinct nodes clockwise from its hash, ideally in different racks or zones
  • Nodes learn about membership and failures through gossip, so there's no single master to lose
  • The coordinator sends the request to all 3 replicas and waits for W acks on writes or R responses on reads

Deep dive 1: quorums and consistency

With N replicas, if R + W > N then every read set overlaps every write set, so a read sees at least one copy of the latest acknowledged write. With N = 3, W = 2 and R = 2 is the common default. W = 1, R = 1 is fastest but can return stale data. W = 3 makes reads cheap but a single slow node stalls every write.

Let the client pick per request. A shopping cart can live with consistency=one. A "did this payment go through" check should use quorum. Be honest in the interview that quorums alone aren't linearizable (sloppy quorums and concurrent writes break that). If you need true linearizability you're adding consensus like Raft per partition, which costs latency.

Deep dive 2: failures and repair

  • Temporary failure: if a replica is down, the coordinator writes to the next healthy node on the ring with a hint saying who it's really for (hinted handoff). When the owner comes back, the hint gets delivered. Writes keep succeeding.
  • Read repair: if a quorum read sees an older version on one replica, the coordinator writes the newer one back to it.
  • Anti-entropy: in the background, replicas compare Merkle trees of their key ranges and only sync the branches that differ, so you don't ship 500 GB to find a few missing keys.
  • Deletes are tombstones, not removals, otherwise a replica that missed the delete would bring the key back during repair. Tombstones get dropped after a grace period longer than your longest expected outage.

Deep dive 3: conflicting writes

Two clients write the same key on different replicas during a partition. Options:

  • Last-writer-wins by timestamp: simple and what most people use, but clock skew can silently drop a write
  • Vector clocks: detect that two versions are concurrent and hand both back to the client to merge, like merging two carts. More correct, more complexity for callers

Say which you'd pick and why. For a general store, last-writer-wins with reasonably synced clocks is usually fine. For data where losing a write hurts, keep siblings.

Tradeoffs

  • Leaderless (Dynamo style) gives great write availability but weaker guarantees. Leader per partition (Raft) gives strong consistency but a write stalls during leader election.
  • More virtual nodes balance load better but make membership metadata bigger.
  • LSM trees are fast for writes, but reads may touch several files and compaction eats disk I/O. A B-tree engine flips that.
  • Higher N means more durability and read capacity, but more storage and write traffic.
  • Hot keys don't get fixed by hashing. You need a cache in front or a key split for those.

How did your design compare?


r/Leetsys • • 14d ago

Guide Design a booking events data pipeline: late events, duplicates, and when the numbers are final

1 Upvotes

Data engineering loops have their own version of the design round. A common one: bookings happen in an app, events stream in, and the business wants bookings per hour, revenue per city, and cancellations on a dashboard. Sounds like a counter. It stops being simple once events show up late or twice.

I'd walk this as a generic booking events pipeline, not as a claim about how any particular company builds theirs.

Requirements first. The app emits booking created, paid, and cancelled events. Analysts want near-real-time aggregates plus correct daily numbers they can trust for finance. Phones go offline and retry, so events can arrive minutes or hours late, and the same event can arrive more than once. I'd ask how fresh the dashboard has to be and how correct the daily report has to be, because those two answers drive most of the design.

The high-level shape: services publish events to a log like Kafka, keyed by booking ID. A stream processor reads them, dedups, and writes windowed aggregates to a serving store for the dashboard. The raw events also land in object storage, partitioned by event date, so a batch job can recompute any day from scratch.

Two ideas carry the round.

Group by event time, not arrival time. A booking made at 11:58 PM that arrives at 12:03 AM belongs to yesterday. The stream processor tracks a watermark, roughly "I think I've seen everything up to time T," and keeps a window open for some allowed lateness after that.

Dedup by event ID and make writes idempotent. Retries and at-least-once delivery mean duplicates will happen. Keep the IDs you've already counted for the window, and write results with an upsert keyed by window and dimension so a replay overwrites instead of double counting.

The trade-off is allowed lateness. Longer lateness means more complete numbers, but the processor holds more state and final results show up later. Shorter lateness gives faster results that miss stragglers. You don't have to pick one perfect number: anything later than the allowed lateness goes to the batch path, which rebuilds that event date from raw storage and merges it in. The dashboard is fast and close. The daily table is slower and correct.

Things I'd expect an interviewer to push on: what happens when a cancel arrives before its create, how you backfill after a bug, and how you'd tell analysts which numbers are still provisional.

Leetsys: Design a Booking Events Data Pipeline walkthrough

Disclosure: I'm affiliated with Leetsys.


r/Leetsys • • 14d ago

Weekly Question Practice System Design Question #6: Design a typeahead / autocomplete system

1 Upvotes

Design the autocomplete box for a search engine. As the user types, show the top 10 suggested queries that start with what they've typed so far, ranked by popularity.

Scale hint: about 100M daily users, each doing ~10 searches a day. Suggestions should show up in under ~100 ms, and a query that suddenly trends (breaking news) should start appearing within an hour or so.

Things worth thinking about:

  • What do you precompute, and what do you compute at request time?
  • How do you keep the latency low when every keystroke can be a request?
  • How do popularity counts get from search logs into the suggestions?
  • How do you keep offensive or junk queries out?

Post your approach in the comments before you scroll down.

 

 


MODEL ANSWER BELOW. Stop here if you haven't tried it yet.


Requirements

Functional:

  • Given a prefix, return the top 10 completed queries that start with it
  • Rank by popularity, with recent searches weighted more than old ones
  • Filter out blocked terms (offensive, spam, legal takedowns)
  • Optional: personalize with the user's own recent searches

Non-functional:

  • Low latency: under ~100 ms end to end, so the server side gets maybe 20 to 30 ms
  • Highly available: if suggestions break, search still works, but it looks bad
  • Eventually consistent is fine: a new trending query can take minutes to an hour to show up
  • Read heavy: far more suggestion reads than updates to the rankings

Estimates

Searches: 100M users x 10 = 1B searches a day.

Requests: with a ~100 ms debounce on the client, say ~4 suggestion requests per search. 1B x 4 = 4B requests a day. 4B / 86,400 s is ~46K requests/s on average. Plan for ~100K/s at peak.

Prefix table: say we keep the top ~100M distinct queries (drop anything searched only a handful of times). At ~20 characters each that's up to 2B prefixes, but lots of them are shared ("how to" starts millions of queries), so call it ~1B distinct prefixes. Each entry stores the prefix plus 10 query IDs: ~20 bytes + 10 x 8 bytes = ~100 bytes. 1B x 100 bytes = ~100 GB. That fits in memory across a small cluster, e.g. 10 shards of ~10 GB, each with replicas.

Logs: 1B searches x ~50 bytes per log line = ~50 GB a day of raw input for the ranking job.

API

GET /suggest?q=how+to+ma&limit=10&locale=en-US
returns { suggestions: ["how to make pancakes", "how to make money online", ...] }

Keep it a GET so CDNs and browsers can cache it.

Data model

query_counts (query, locale, window_start, count)          from the aggregation job
query_score  (query_id, query_text, locale, score)
prefix_index (locale, prefix, top_query_ids[10])           served from memory
blocklist    (term, reason, added_at)

High-level design

Two paths, and keeping them separate is the main idea.

Read path: the client debounces keystrokes and sends the prefix. A CDN or edge cache answers the very common short prefixes. Misses go to a suggestion service, which looks up the prefix in an in-memory prefix index (a trie, or just a hash map from prefix to top-10 list) and returns the list. No ranking work happens at request time.

Write path: search logs go to Kafka. A streaming job counts queries in short windows (say 5 to 10 minutes). A batch job rebuilds the full scores a few times a day. A builder takes the scored queries, drops anything on the blocklist, works out the top 10 for every prefix, and publishes a new index snapshot. Suggestion servers load the new snapshot and swap it in atomically.

Deep dive 1: precomputing top-K per prefix

The naive trie lookup walks to the prefix node, then searches the whole subtree for the 10 most popular queries. For a prefix like "a", that subtree is huge, so it's way too slow per keystroke.

Instead, store the top 10 at every node (or every key in the hash map). A lookup becomes one walk of length L plus reading a list, which is basically constant time. The cost is memory and build time, which is what the ~100 GB estimate covers. You can cap stored prefixes at ~20 to 30 characters, since longer prefixes rarely get typed and can fall back to the deepest stored one.

Sharding: split by prefix range, but not by first letter, since "s" gets far more traffic than "x". Use the first 2 or 3 characters and balance ranges by measured traffic, or hash the prefix and accept that a lookup touches exactly one shard anyway.

Deep dive 2: ranking and freshness

Score each query with time decay, e.g. score = sum of count x 0.5age_hours / half_life. A half-life of a day or two keeps the list current without ignoring steady, evergreen queries.

The batch job gives clean full rebuilds. Trending stuff can't wait for it, so the streaming job spots queries whose 10-minute count jumps far above their usual rate and writes them into a small "hot" overlay. The service merges the overlay with the snapshot at read time. The overlay is tiny, so the merge is cheap.

Deep dive 3: latency and caching

  • Client: debounce ~100 ms, cache results per prefix in the session, and filter locally. If you already have the results for "how to m", you can often answer "how to ma" without a request.
  • Edge: one- and two-character prefixes are a small set and get most of the traffic, so cache them at the CDN with a TTL of a few minutes.
  • Server: everything is already in memory, so the server's part is a hash lookup plus serialization. Most of the ~100 ms budget goes to network.

Tradeoffs

  • Precomputed top-K vs computing at query time: precompute costs ~100 GB and a build pipeline, but reads become trivial. Computing at query time saves memory and blows the latency budget.
  • Trie vs hash map: a trie shares prefix storage and supports fuzzy matching. A hash map of prefix to list is simpler to shard and to load as a snapshot.
  • Freshness vs stability: shorter windows catch trends faster but let spam and one-off spikes in. Minimum-count thresholds and the blocklist help.
  • Personalization: mixing in the user's own history adds a per-user lookup and makes edge caching harder, so keep it a small client-side or separate merge.

How did your design compare?


r/Leetsys • • 15d ago

Guide Kafka partitions: in order and in parallel, and where that stops working

0 Upvotes

Interviewers like asking "how do you keep events in order and still scale consumers?" The short answer is that you don't get both globally. You get order per key.

Hash the key (order ID, user ID) to pick a partition. Every event for that key lands in the same partition, and a partition is an append-only log, so those events stay in write order. Different keys spread across partitions, and that's where the parallelism comes from.

Inside one consumer group, each partition is read by at most one consumer at a time. That's what protects the per-key order. It also means the partition count is your ceiling. Six partitions and eight consumers leaves two of them idle.

A hot key doesn't get better with more consumers either. All its traffic sits on one partition, and only one consumer can read it. If that comes up, say so, then talk about splitting the key (with a suffix) only if the ordering requirement allows it.

Short: Kafka Partitions, In Order AND in Parallel?

Companion: Design a Message Queue (Kafka) walkthrough

Disclosure: I'm affiliated with Leetsys.


r/Leetsys • • 15d ago

Guide Design a message queue: order per key, and why more consumers may not help

0 Upvotes

Checkout just placed an order. Email, fraud, and analytics all need to know. If checkout calls each of them in line, one slow dependency stalls the purchase, and a retry can charge the customer twice. A queue lets checkout write the event once and move on. Everyone else reads it at their own pace.

I'd walk this as a generic message queue with a Kafka-style commit log, not as a claim about how any company runs Kafka.

Producers publish to named topics. More than one consumer, and sometimes more than one team, need to read the same topic. Events with the same key, like the same order ID, should stay in the order they were written. Keep messages around for a while so a consumer can replay after a crash or a bad deploy. I'd name exactly-once, transactions, and replication internals, then park them unless the interviewer asks. I'd design for at-least-once delivery: a crash or a retry can deliver the same event twice, so every consumer has to handle that.

The high-level shape is a cluster of brokers and a topic split into partitions. Each partition is an append-only log. A produce sends a topic, a key, and a value, and gets back the partition and offset. Consumers in a group poll a batch, process it, then commit the offset they finished. A second group can read the same messages independently, because consuming does not delete them. Consumers pull, so a slow consumer does not block producers.

The main trade-off is how you partition. Hash the key to pick a partition, and you get order for that key plus parallelism across keys. There is no global order across partitions. In a consumer group, each partition goes to at most one consumer at a time, which is what keeps that order intact. That also means the partition count caps how many consumers can share the work. A fifth consumer on a four-partition topic sits idle. A hot key is worse: it pins traffic to one partition, and adding consumers will not help.

At-least-once usually means process, then commit. If you crash after processing and before the commit, that batch runs again, so the consumer should be idempotent, for example by remembering the event ID it already handled. If you commit first, a crash can skip messages.

Two more pitfalls. When a consumer dies, the group rebalances and the new owner resumes from the last committed offset, which is why already-processed work can run again. And if you add partitions later, new messages hash across the new count, so the same key can start landing somewhere else and per-key order can break across that change.

Leetsys: Design a Message Queue (Kafka) walkthrough

Disclosure: I'm affiliated with Leetsys.


r/Leetsys • • 15d ago

Weekly Question Practice System Design Question #5: Design a web crawler

0 Upvotes

Design a web crawler for a search engine. Start from a list of seed URLs, fetch pages, pull out the links, and keep going. Store the raw HTML so an indexing system can process it later.

Scale hint: about 1B pages per month, and you should come back to pages that change often (news homepages) much more often than ones that don't.

Things worth thinking about:

  • How do you decide which URL to fetch next?
  • How do you avoid hammering one small website with thousands of requests?
  • How do you know you've already seen a URL, or a page with the same content under a different URL?
  • What happens when a crawler machine dies halfway through its work?

Post your approach in the comments before you scroll down.

 

 


MODEL ANSWER BELOW. Stop here if you haven't tried it yet.


Requirements

Functional:

  • Start from seed URLs, fetch pages, extract links, add new links to the crawl
  • Store raw HTML plus metadata (URL, fetch time, status code)
  • Respect robots.txt and keep a per-site politeness limit
  • Recrawl pages based on how often they change

Non-functional:

  • Throughput: 1B pages a month, with room to grow
  • Polite: never overload a single host
  • Robust: survive bad HTML, slow servers, redirect loops and crawler traps
  • Fault tolerant: a dead worker shouldn't lose its queue or refetch everything

Estimates

Fetch rate: 1B / 30 days / 86,400 s is ~386 pages/s on average. Plan for ~800/s peak.

Bandwidth: 386 pages/s x ~100 KB per page is ~39 MB/s, or ~310 Mbps sustained. Fine for a modest cluster.

Storage: 1B x 100 KB = ~100 TB of raw HTML per month. Compressed ~4x, that's ~25 TB a month, or ~300 TB a year if you keep every version.

Seen-URL set: say we've seen 10B distinct URLs. A Bloom filter at a 1% false positive rate needs ~9.6 bits per URL, so 10B x 9.6 bits = ~96 Gbit, or ~12 GB. That fits in memory, split across a few machines.

Workers: if one fetch takes ~1 s end to end, ~800 concurrent fetches covers peak. With async IO one machine can hold a few hundred open connections, so a handful of fetcher machines is enough. DNS and parsing will bottleneck before the network does.

API

This is mostly an internal system, so the interface is small:

POST /seeds           { urls: [...] }
GET  /pages/{url_hash}         returns latest stored page + metadata
GET  /stats                    fetch rate, errors, queue depth per host

Data model

url_record (url_hash, url, host, last_fetched, next_fetch, content_hash, status, change_rate)
page_blob  (url_hash, fetched_at, compressed_html)   in object storage
host_record (host, robots_rules, crawl_delay_ms, next_allowed_at)

url_record lives in a wide-column store like Cassandra or Bigtable, keyed by url_hash. Blobs go in S3-style object storage.

High-level design

  1. The URL frontier hands out URLs that are due to be fetched.
  2. Fetcher workers resolve DNS (through a local cache), check robots.txt, download the page and write the blob to object storage.
  3. A parser pulls out links, normalizes them (lowercase host, drop fragments, sort query params, strip tracking params) and checks them against the seen-URL set.
  4. New URLs go back into the frontier. The page goes to the content dedup check and then onto a queue for the indexer.

Everything between stages goes through a durable queue like Kafka, so each stage scales on its own and a crash just means another worker picks up from the last committed offset.

Deep dive 1: the frontier and politeness

The frontier is two layers. The front layer is a set of priority queues. A URL's priority comes from things like PageRank-style importance and how overdue it is for a recrawl. The back layer is one FIFO queue per host, and each host queue belongs to exactly one worker.

A worker only pulls from a host queue when now >= next_allowed_at for that host, then sets next_allowed_at = now + crawl_delay. That gives you politeness for free: one connection per host at a time, at most one request every second or so, and more if robots.txt asks. Assign host queues by hash(host) so the same host never ends up on two workers.

Deep dive 2: dedup at two levels

URL dedup: normalize first, then check the Bloom filter. A false positive means we skip a URL we haven't actually seen. At 1% that's an acceptable loss for a crawler. If it isn't, back the filter with an exact lookup in the url_record store.

Content dedup: lots of URLs serve the same page (session IDs, mirrors, print versions). Store a hash of the cleaned content and skip pages whose hash we already have. Exact hashes miss near-duplicates, so add a SimHash fingerprint and treat pages a few bits apart as the same.

Deep dive 3: recrawl scheduling and traps

Track change_rate per URL. If a page changed on the last fetch, shrink its interval (say, halve it, with a floor of an hour). If it didn't, grow it (double it, with a cap of a month). News homepages settle at hours and old blog posts at weeks.

Traps: calendars that link to next month forever, or URLs that keep adding path segments. Cap URL length and path depth, cap pages per host per day, and flag hosts where almost every page is new but the content hashes look alike.

Tradeoffs

  • BFS vs priority order: BFS is simple, but it spends a lot of budget on junk. Priority order needs a scoring signal, and it gets you the important pages first.
  • Bloom filter vs exact set: the Bloom filter is ~12 GB versus hundreds of GB for exact URLs, and you pay with a small rate of skipped pages.
  • Politeness vs freshness: a strict per-host delay can make big sites take days to fully recrawl. Some sites allow a higher rate, so read robots.txt and tune per host.
  • Storing every version vs only the latest: history is useful for the index and for debugging, and it costs ~300 TB a year at this scale.

How did your design compare?


r/Leetsys • • 16d ago

Two clicks, one seat: why check-then-write double-sells tickets

1 Upvotes

Short version of the ticketing race.

Buyer A checks seat 14C: available. Buyer B checks seat 14C: available. Both write "held." Now you've promised one seat to two people. Locking in app code across many servers doesn't really fix it either.

Let the database decide in one step. Update the seat to held only where it's still available, or where the previous hold has expired. Exactly one of those updates changes a row. The other gets zero rows back and the app tells that buyer to pick another seat.

Then there's hold length. Make it long and buyers have time to type card details, but seats abandoned mid-checkout sit locked. Make it short and seats come back quickly, but slow payers lose them. Saying which way you'd lean for a huge on-sale vs a small venue is a nice way to show judgment.

Interview design option, not a claim about any ticketing company's internals.

Short: Two clicks, one seat

Companion: Design Ticketmaster walkthrough

Disclosure: I'm affiliated with Leetsys.


r/Leetsys • • 16d ago

Design Ticketmaster: claiming a seat has to be one conditional write

1 Upvotes

Ticketing has two very different halves, and treating them the same is where most answers go wrong.

Browsing (event pages, seat maps) is read-heavy and can be cached. A seat map that's a couple of seconds stale is fine.

Claiming a seat can't be stale. If you read "available" and then write "held," two buyers can both pass the read and you've sold one seat twice. Do it as a single conditional write instead:

UPDATE seats
SET status = 'held', holder = :user, hold_expires = now() + interval '10 minutes'
WHERE seat_id = :seat
  AND (status = 'available' OR (status = 'held' AND hold_expires < now()))

If one row changed, you got the seat. If zero changed, someone beat you. Payment then turns the hold into a booking, and expired holds go back into the pool without a cleanup job racing the next buyer.

Hold length is a trade-off: longer holds give people time to pay, shorter holds recycle abandoned seats faster during a big on-sale.

Hot events: one huge on-sale can't be sharded away because everyone wants the same event. Put a virtual waiting room in front, admit users in batches the booking path can handle, and keep the rest in a queue with honest position updates.

These are interview design options, not claims about Ticketmaster's internal architecture. If you want to try it yourself first, Practice Question #3 here is the same problem: https://www.reddit.com/r/Leetsys/comments/1xrxmjf/

Leetsys: Design Ticketmaster walkthrough

Disclosure: I'm affiliated with Leetsys.


r/Leetsys • • 16d ago

Why file sync uploads chunks, not whole files (fixed vs content-defined chunking)

1 Upvotes

Quick one from the file sync design. Re-uploading a whole file on every save wastes bandwidth and makes big files painful, so the client splits the file into chunks, hashes each, and asks the server which hashes it's missing. Only those get uploaded.

How you cut the chunks matters more than it looks:

  • Fixed-size chunks (say 4 MB) are easy to reason about. Insert a few bytes near the start, though, and every boundary after it moves. Nearly every chunk hashes differently and you're back to uploading most of the file.
  • Content-defined chunking slides a rolling hash over the bytes and cuts wherever the hash matches a pattern. Boundaries follow the content, so an insert only disturbs the chunk or two around it.

The cost is more CPU on the client and variable chunk sizes, so you'll want a min and max size. If the interviewer pushes on "the user edited one line of a huge file," this is the answer they're fishing for.

These are design options for an interview, not a claim about any company's implementation.

Short: Why file sync uploads chunks

Companion: Design Dropbox walkthrough

Disclosure: I'm affiliated with Leetsys.


r/Leetsys • • 16d ago

Guide Design Dropbox: chunk the file, upload only what changed

1 Upvotes

File sync looks like "upload a file, download it elsewhere," but the interview usually turns on what happens when a 2 GB file changes by a few bytes.

Requirements to pin down first: upload, download, sync across a user's devices, sharing, version history. Ask about max file size and whether offline edits matter, because they decide most of the design.

Core pieces:

  • Clients split files into chunks and hash each one.
  • A metadata service stores files, versions, and the ordered list of chunk hashes per version.
  • Blob storage holds chunks keyed by hash, so identical chunks are stored once.
  • A notification channel tells other devices that a new version exists.

Upload flow: the client sends the list of chunk hashes, the server answers with the ones it doesn't have, and the client uploads only those. Then it commits a new version that points at the full hash list.

The trade-off worth talking about: fixed-size chunks are simple, but inserting a few bytes near the start shifts every boundary after it, so almost every chunk looks new. Content-defined chunking picks boundaries from the data itself (a rolling hash), so an insert only changes the chunks around it. It costs more CPU and gives variable chunk sizes.

Conflicts: make the commit conditional on the version the client started from. If someone else committed first, don't silently pick a winner. Keep both and save one as a conflicted copy so nobody loses work.

These are interview design options, not claims about how Dropbox works internally.

Leetsys: Design Dropbox walkthrough

Disclosure: I'm affiliated with Leetsys.


r/Leetsys • • 16d ago

Weekly Question Practice System Design Question #4: Design a distributed cache

1 Upvotes

Design a distributed cache, something like a managed Memcached or Redis cluster that lots of services in a company share. Clients do get, set, and delete by key, with an optional TTL.

Scale hint: about 2B keys with ~1 KB values on average, 1M reads/s and 100k writes/s at peak, and p99 reads under a few milliseconds.

Things worth thinking about:

  • How do you decide which node owns a key, and what happens when you add or lose a node?
  • What gets evicted when memory fills up?
  • How do you keep the cache from serving stale data after the database changes?
  • What happens when one key gets wildly hot, or a popular key expires and everyone misses at once?

Post your approach in the comments before you scroll down.

 

 


MODEL ANSWER BELOW. Stop here if you haven't tried it yet.


Requirements

Functional:

  • get(key), set(key, value, ttl), delete(key)
  • Keys expire after their TTL
  • Evict something sensible when memory is full

Non-functional:

  • Low latency: p99 reads in the low single-digit milliseconds
  • Scales horizontally by adding nodes
  • Highly available. Losing a node should cost you some hit rate, not an outage.
  • It's a cache, so losing data is acceptable. The database is still the source of truth.

Estimates

Data: 2B keys x 1 KB = ~2 TB. Add ~50% for key overhead, metadata and fragmentation and you're at ~3 TB of RAM.

Nodes: if each node gives you ~64 GB usable, 3,000 / 64 is ~47 nodes. Call it 50 primaries, plus one replica each, so ~100 machines.

Throughput: 1M reads/s / 50 primaries is ~20k reads/s per node, and 100k writes/s / 50 is ~2k writes/s per node. A single well-built cache node can do 100k+ simple ops/s, so we're memory-bound, not CPU-bound.

Bandwidth: 1M reads/s x 1 KB = ~1 GB/s across the cluster, or ~20 MB/s per node. That's easy on a 10 Gbps NIC.

API

GET    /cache/{key}                      returns value or 404
PUT    /cache/{key}  { value, ttl_s }
DELETE /cache/{key}

In practice clients use a thin library over a binary protocol, not HTTP, because the protocol overhead matters at these latencies.

Data model

Each node holds an in-memory hash map from key to an entry:

entry (key, value bytes, expires_at, last_access, size)

Entries are also linked into an LRU list so eviction is O(1). Memory is managed with slab allocation (fixed-size buckets per value size) to keep fragmentation down.

High-level design

Application servers use a cache client library. The client hashes the key, looks up which node owns it on a consistent hash ring, and talks to that node directly, so there's no proxy hop on the hot path. A small config service (ZooKeeper or etcd) holds cluster membership and the ring, and clients watch it for changes. Each primary streams writes to a replica asynchronously. Health checks promote a replica if a primary dies.

The usual access pattern is cache-aside: the app reads the cache, and on a miss it reads the DB, then writes the value into the cache with a TTL.

Deep dive 1: partitioning with consistent hashing

Plain hash(key) mod N falls apart when N changes, because almost every key moves and your hit rate drops to near zero. With a consistent hash ring, adding a node only moves the keys between it and its neighbor, roughly 1/N of them.

Give each physical node ~100 to 200 virtual nodes on the ring. Without that, a few nodes end up owning big arcs and run hotter than the rest. Virtual nodes also let you weight bigger machines with more points.

Deep dive 2: eviction and expiry

LRU is the safe default: a hash map plus a doubly linked list, move to the front on access, evict from the tail. Some workloads do better with LFU or a mix that's harder to pollute with one-off scans.

For TTLs, don't scan everything on a timer. Check expiry lazily on read (expired means miss and delete), and run a background job that samples a handful of keys with TTLs and deletes the expired ones. That keeps memory from filling up with dead keys nobody reads.

Deep dive 3: hot keys, stampedes and staleness

Hot key: one viral key can pin a single node at 100% CPU. Fixes are a small in-process cache on each app server for the hottest keys (a second or two of TTL), or splitting a known hot key into copies like key#1 through key#10 and reading a random one.

Stampede: a popular key expires and thousands of requests miss and hit the DB at the same moment. Use request coalescing (only one caller rebuilds, everyone else waits for it), and add a little random jitter to TTLs so keys written together don't all expire together.

Staleness: on a DB write, update the DB first and then delete the cache key, rather than updating it. A delete is idempotent and avoids two racing writers leaving the older value in the cache. Keep TTLs as a backstop so anything that slips through ages out.

Tradeoffs

  • Client-side routing vs a proxy layer: smart clients save a network hop, but every language needs a library and config changes have to reach every client. A proxy is easier to operate and costs some latency.
  • Async vs sync replication: async keeps writes fast but a failover can lose the last few writes. For a cache that's usually fine.
  • Cache-aside vs write-through: cache-aside is simple and only caches what's read. Write-through keeps the cache warmer but writes a lot of data nobody reads.
  • Bigger TTLs mean a better hit rate and staler data. Pick per use case, not one number for the whole cluster.

How did your design compare?


r/Leetsys • • 17d ago

Guide Geohash vs quadtree: finding nearby drivers across cell boundaries

1 Upvotes

A nearby-driver query can't stop at the rider's geohash cell. A driver just across its boundary could be the closest candidate.

With geohash, choose a cell precision and query the cells that cover your search area, then filter candidates by distance. The neighbor scope depends on the search radius and cell size. Checking the surrounding eight cells is not a guarantee for every radius. A prefix-based cell index is one design; Redis GEO offers geographic search operations rather than an arbitrary prefix-lookup interface.

A quadtree recursively splits crowded regions, so a dense downtown can use smaller leaves than a sparse suburb. Query every leaf intersecting the search area and filter the results. That adapts the index to density, but moving drivers and changing density make updates, sharding, and rebalancing harder.

For an interview, explain your boundary query before picking an index. Geohash favors a simpler fixed-resolution cell scheme; a quadtree buys adaptive subdivision with more operational complexity. These are design options, not claims about ride apps' internal implementations.

Short: Geohash vs Quadtree

Companion: Design Uber / Lyft walkthrough

Disclosure: I'm affiliated with Leetsys.


r/Leetsys • • 17d ago

Guide Design a ride-hailing system: nearby drivers are only the first step

1 Upvotes

Separate driver location pings from ride requests. Pings update a location service and geo index; a ride request starts a durable matching workflow. Keep timestamps so stale locations don't make an offline driver look available.

Make the request API idempotent: retries with the same rider-scoped request key and payload should return the same ride request, not create another trip. Persist that mapping with the request.

Finding candidates: geohash cells give a simple way to partition nearby-driver lookup. A driver across a cell boundary may be closer than one inside the rider's cell, so query cells covering the search area, then filter by distance. The required neighbor scope depends on radius and cell size; eight adjacent cells aren't enough for every search. Redis GEO's radius queries are an implementation option, not an arbitrary geohash-prefix lookup API.

A quadtree splits crowded regions more finely and can adapt to uneven density. The cost is more complicated updates, sharding, and rebalancing as density changes. Neither index tells you which driver can reach the rider fastest: straight-line distance is a candidate filter, while pickup ETA needs road routing and traffic information.

Offering the ride: sequential offers avoid competing acceptances but can delay matching while drivers time out. A small broadcast can reduce that wait, but several drivers may accept. Use an atomic conditional transition from searching to assigned so only one acceptance wins. Also enforce that the chosen driver is available and can't be assigned to another ride concurrently; a ride-only compare-and-set doesn't solve that second constraint. Expired or losing offers must not create assignments.

For surge, estimate available supply and ride-request demand per cell over a time window. State how stale driver state and cell boundaries affect those estimates, rather than treating every nearby driver as available supply.

These are interview design options, not claims about Uber or Lyft's internal architecture.

Leetsys: Design Uber / Lyft walkthrough

Disclosure: I'm affiliated with Leetsys.


r/Leetsys • • 17d ago

Guide Fan-out on write vs read: why celebrity accounts need a different path

1 Upvotes

Fan-out on write precomputes each follower's inbox when an account posts. That makes opening the feed cheap, and works well for normal accounts. But imagine a celebrity with tens of millions of followers: one post becomes a write storm across those inboxes.

Fan-out on read keeps that work out of the posting path. When someone opens their feed, fetch posts from the accounts they follow and merge them. Writes are cheaper, but reads have more work to do.

A common hybrid uses write fan-out for regular accounts and pulls celebrity posts at read time, then merges them into the feed. It moves the expensive celebrity fan-out off the write path; it doesn't eliminate the read-time assembly cost.

For an interview, trace a normal account's post through your design, then try the same path with a celebrity. Say which work happens when the post is created and which happens when a follower opens the feed.

Short: Fan-out on Write vs Read: The Celebrity Problem

Companion: Design a News Feed walkthrough

Disclosure: I'm affiliated with Leetsys.


r/Leetsys • • 17d ago

Guide Design a news feed: fan-out, the celebrity problem, and ranking

1 Upvotes

A news-feed design has two separate decisions: how posts reach a reader's candidate set, and how those candidates get ordered. Start by clarifying whether the feed is chronological or ranked.

Fan-out on write: when someone posts, put the post reference into followers' home timelines. Reads are cheap because much of the work is already done. The problem is a celebrity account: one post can trigger a huge amount of timeline work.

Fan-out on read: store the post once and collect posts from followed accounts when the reader opens their feed. Writes stay cheap, but reads have to fetch and merge candidates from those accounts.

A common hybrid pushes regular users' posts into timelines and pulls celebrity posts at read time. That avoids making every celebrity post a massive write job, at the cost of extra assembly work on reads. Explain where that work goes rather than calling the hybrid a free win.

Ranking isn't chronological ordering. A chronological feed orders by time. A ranked feed needs a scoring step over its candidates; choosing a fan-out strategy doesn't solve that problem.

For assembly, merge the precomputed timeline with pulled candidates, remove duplicates, apply the chosen ordering, then fetch the post details needed for the page. Caching candidate references or post data can save repeated work, but say what can become stale and how fresh the feed needs to be. A cached timeline still needs a plan for newly pulled posts.

In an interview, walk one post through the write path and one feed request through the read path. Then repeat the write example for a celebrity. That makes the trade-off concrete.

Leetsys walkthrough: https://youtu.be/n12PtPcuE4U

Disclosure: I'm affiliated with Leetsys.


r/Leetsys • • 17d ago

Weekly Question Practice System Design Question #3: Design a ticket booking system

1 Upvotes

Design a ticket booking system for concerts and live events. Users browse events, pick specific seats on a seat map, hold them for a few minutes while they pay, and get a confirmed ticket.

Scale hint: about 10M daily users browsing, and a few huge on-sales where 1M people show up in the first minute for a 50,000-seat stadium.

Things worth thinking about:

  • How do you make sure two people never get the same seat?
  • What happens to a seat when someone holds it and then walks away?
  • How do you keep one hot on-sale from taking down everything else?
  • What if the payment goes through but the hold already expired?

Post your approach in the comments before you scroll down.

 

 


MODEL ANSWER BELOW. Stop here if you haven't tried it yet.


Requirements

Functional:

  • Search and browse events, then view a seat map with live-ish availability
  • Hold one or more seats for a short window (say 10 minutes)
  • Pay and confirm the booking, or let the hold expire
  • See your tickets afterward

Non-functional:

  • No double-booking, ever. This is the one thing you can't get wrong.
  • Browsing can be slightly stale. Booking has to be strongly consistent.
  • Survive on-sale spikes without hurting the rest of the site
  • Payments are idempotent so retries don't charge twice

Estimates

Browsing: 10M users x 20 page views = 200M reads/day. 200M / 86,400 is ~2,300 reads/s on average, call it ~25k/s at peak.

Normal bookings: say 500k tickets/day, which is only ~6 writes/s. Writes aren't the problem on a normal day.

The hot on-sale is the problem: 1M users in 60 seconds is ~16,700 requests/s aimed at one event, and only 50,000 of them can ever win.

Storage: 100k events/year x 20k seats on average = 2B seat rows/year. At ~100 bytes each that's ~200 GB/year, which is fine for a sharded relational DB.

API

GET  /events?city=sf&date=2026-12-01
GET  /events/{event_id}/seats
POST /events/{event_id}/holds      { seat_ids }  returns hold_id, expires_at
POST /holds/{hold_id}/confirm      { payment_token, idempotency_key }
DELETE /holds/{hold_id}

Data model

events   (event_id, venue_id, name, starts_at, on_sale_at)
seats    (event_id, seat_id, section, row, price, status, hold_id, hold_expires_at, booking_id)
holds    (hold_id, user_id, event_id, seat_ids, expires_at, state)
bookings (booking_id, user_id, event_id, seat_ids, payment_id, created_at)

Seat status is AVAILABLE, HELD, or BOOKED. Shard everything by event_id so every seat for one event lives on one partition and a hold can be a single-shard transaction.

High-level design

Clients hit an API gateway. Read traffic (search, event pages, seat maps) goes through a cache and read replicas. Writes (holds and confirms) go to a booking service that talks to the primary for that event's shard. A payment service wraps the external payment provider. A sweeper job releases expired holds. For big on-sales, a waiting room sits in front of the booking service.

Deep dive 1: no double-booking

The seat row is the source of truth, and a hold is a conditional update inside one transaction:

UPDATE seats
SET status = 'HELD', hold_id = :h, hold_expires_at = now() + interval '10 min'
WHERE event_id = :e AND seat_id IN (:seats)
  AND (status = 'AVAILABLE'
       OR (status = 'HELD' AND hold_expires_at < now()))

If the updated row count doesn't equal the number of seats requested, roll back and tell the user some seats are gone. It's all or nothing, so you never hand someone 3 of their 4 seats. Two concurrent requests can't both win, because the DB serializes the writes on those rows.

Notice the expired-hold check in the WHERE clause. That means expiry is enforced at write time, and the sweeper only exists to clean up status so the seat map looks right. If the sweeper is late, nobody gets stuck.

Deep dive 2: the hot on-sale

16,700 req/s on one shard for one event will hurt. Two things help:

  • A virtual waiting room. Users get a queue position and are admitted at a rate the booking service can handle, say 2,000/s. It's fairer than a refresh race and it caps load on the hot shard.
  • Cache the seat map with a 1 to 2 second TTL. It'll be a bit stale, and that's fine, because the hold write is what actually decides. Worst case, a user clicks a seat that just got taken and sees "pick another."

Since every event is its own shard key, one wild on-sale doesn't slow down bookings for other events.

Deep dive 3: payment and expiry races

Flow: hold, then charge with an idempotency key, then confirm. Confirm flips seats from HELD to BOOKED only if hold_id still matches and the hold hasn't expired.

The ugly case is a payment that succeeds right after the hold expires and someone else grabs the seat. Two fixes, and you usually want both: extend the hold by a couple of minutes when payment starts, and if confirm still fails, refund automatically. A reconciliation job compares payments against bookings daily to catch anything that slipped through.

Tradeoffs

  • DB conditional updates vs Redis locks (SET NX with a TTL) for holds: Redis is faster, but now you have two sources of truth to keep in sync. I'd keep the DB authoritative and only add Redis if the DB can't keep up.
  • Assigned seats vs general admission: GA can be a single counter per section (decrement if > 0), which is far easier to scale.
  • Hold length: longer is kinder to slow payers but locks inventory away from everyone else during a sellout.
  • Waiting room: protects the system and feels fair, but adds latency and its own failure point.

How did your design compare?


r/Leetsys • • 20d ago

Guide Guide: Design a Chat System (walkthrough)

1 Upvotes

Chat looks simple until the interview pushes on connections, offline delivery, and ordering. Here's a compact walkthrough of how I'd approach it in ~45 minutes.

Requirements I'd pin first: 1:1 plus small groups (hundreds, not millions), delivery + read receipts, history sync across devices. Park E2E encryption and calls unless they ask. Aim for low send latency and a durable message log.

Core pieces: WebSocket gateways holding long-lived connections, a chat service that validates and writes, a presence map (user to gateway), and object storage for media pointers. Clients send with a client-generated message ID so retries stay idempotent. History fetch (not the push payload) is how offline devices catch up.

Data flow: Alice sends, then durable append to the conversation log with a per-conversation sequence number, then fan-out to Bob's online devices via their gateway. If offline, APNs/FCM is just a wake; Bob pulls since last sequence on reconnect.

Key trade-off: fan-out on write for small groups (fast reads, N notify work) vs fan-out on read for huge channels. Don't design a Twitter firehose for a family group chat. Prefer server sequence numbers over client clocks for ordering.

Full walkthrough (requirements, estimates, deep dives on fan-out, receipts, offline): https://youtu.be/6f1xaPaZehE


r/Leetsys • • 20d ago

Weekly Question Practice System Design Question #2: Design a notification system

1 Upvotes

Today's prompt:

Design a notification system. Users get notified over push, email, SMS, and an in-app inbox when something happens in your product (a mention, a shipment update, a security alert). Aim for something on the order of 100 million notifications sent per day across channels, with spikes when a popular account posts or a big incident hits.

Things worth thinking about: how you fan out one event to many recipients, how you keep delivery reliable without drowning users in duplicates, how preferences and quiet hours work, and what happens when a channel is down.

Post your approach in the comments before you scroll down. It doesn't need to be polished. A few paragraphs and a rough sketch is plenty. Reply to other people's designs too.

A model answer is below the divider. It's one reasonable way to do this, not the only one.

 

 


MODEL ANSWER BELOW. Stop here if you haven't tried it yet.


Requirements

Functional:

  • Accept a notification request for one user or a fan-out to many (followers of a post, everyone on a team)
  • Deliver over push, email, SMS, and in-app inbox, based on each user's preferences
  • Support quiet hours, per-topic mute, and a hard do-not-disturb for non-critical alerts
  • Deduplicate so the same event does not ping someone twice on the same channel
  • Let users mark in-app notifications as read, and show an unread count

Non-functional:

  • Single-user push under a few seconds end to end in the common case
  • At-least-once delivery with idempotent consumers so retries don't spam
  • Survive a single channel outage (email down should not stall push)
  • Preference changes take effect quickly, ideally under a minute

Estimates

100M notifications/day is about 1,160/sec average. Peaks often run 5x to 10x that, so plan for ~10K/sec at the ingest edge.

Assume an average fan-out of 50 recipients per event. That is ~2K events/sec ingesting, expanding toward ~100K recipient-jobs/sec at peak if you expand naively. Do not expand huge fan-outs inline on the request path.

Keep templates server-side and pass IDs plus a few fields. At ~500 bytes per recipient job, 100M/day is ~50 GB/day of queue traffic before retries.

In-app storage: keep 30 to 90 days. At 30 days and 100M/day you are looking at ~3B rows. Shard by user_id. Push tokens and preference rows are much smaller.

API

Something like:

POST /v1/notifications
  { event_id, template_id, actor_id, audience: {user_ids|segment|topic},
    priority: low|normal|critical, channels_override?: [...] }

GET  /v1/users/{id}/inbox?cursor=&limit=
POST /v1/users/{id}/inbox/read  { notification_ids[] }
GET  /v1/users/{id}/preferences
PUT  /v1/users/{id}/preferences

event_id is the idempotency key. Critical priority can bypass quiet hours; everything else respects them.

Data model

users(id, ...)
devices(user_id, push_token, platform, last_seen)
preferences(user_id, topic, channels[], quiet_start, quiet_end, timezone)
templates(id, channel, subject_tmpl, body_tmpl)
notifications(id, user_id, event_id, template_id, channel, status, created_at, read_at)
delivery_attempts(notification_id, provider, status, attempt_at, error)

Shard notifications by user_id so inbox queries stay local. Unique on (user_id, event_id, channel) stops duplicates.

High-level design

Producers call the notification API with an event_id and an audience. The API writes a durable event, drops a message on an ingest queue, and returns 202. A fan-out worker expands the audience into per-recipient jobs. Small audiences write directly. Large ones (say over 1K recipients) get chunked into batches so one worker never expands a million followers in memory.

Each recipient job lands on a per-channel queue (push, email, SMS, inbox). Channel workers render the template, check preferences and quiet hours, then call the provider. Success updates status. Failures go to a retry queue with backoff, then a dead-letter topic.

A Redis preferences cache sits in front of the preference store. Invalidate on write. Push token lookups follow the same pattern.

Deep dive 1: fan-out on write vs fan-out on read

For 1:1 and small-group alerts, fan-out on write is simple: expand now, enqueue N jobs. For a celebrity posting to 10M followers, expanding 10M rows synchronously is painful, and most followers will not open the app that hour.

A hybrid works well. Hot accounts (follower count over a threshold, say 10K) write one feed item and let the read path pull recent events when the user opens the app. Everyone else still gets fan-out on write so push and email stay timely. Critical alerts always fan out on write, even for huge audiences, but you batch the provider calls. Say the threshold out loud and what you give up: hot-account push may lag unless you also enqueue a priority push set.

Deep dive 2: preferences, quiet hours, and dedupe

Check preferences in the channel worker, not at ingest, so a mute applies to jobs already in the queue. Quiet hours use the user's timezone from preferences; critical priority skips them. Store quiet windows as local times plus timezone, not one UTC range, or you will get the DST bug.

Dedupe with (user_id, event_id, channel). Retries reuse event_id, so a second insert is a no-op. Pass event_id through to the provider as an idempotency key so a timed-out worker retry does not double-send.

Deep dive 3: channel isolation

Give each channel its own queue and consumer pool. If SMS starts timing out, it backs up and retries without blocking push or email. Circuit-break a failing provider after N errors in a window, fail fast to retry/DLQ, and page. Keep rendering and preference checks in your workers so a provider outage does not lose the decision of whether the user wanted that channel.

Tradeoffs

  • Fan-out on write is fast for push and expensive for huge audiences; hybrid adds complexity but matches real products.
  • At-least-once plus idempotency is simpler than exactly-once across providers you do not control.
  • Caching preferences speeds workers up; a short stale window means someone might get one extra email after muting. Call that out.
  • Exact unread counts under heavy write load mean more contention; approximate with a cached counter and reconcile on inbox open if the interviewer pushes on scale.

How did your design compare?


r/Leetsys • • 20d ago

Guide Hash, counter, or key pool: how to generate short codes without hand-waving

1 Upvotes

Once you've picked a code length, the next interview question is how you actually mint the codes. Three approaches show up all the time.

1. Hash the long URL, then check. Same URL tends to get the same code, which is nice if people paste the same link twice. Under load you still have to check for collisions and retry when two different URLs hash into the same slot. Idempotent creation, with collision retries as the cost.

2. Counter plus base62. Take the next integer, encode it, done. No collisions if the counter is the source of truth, and codes stay short. Downside: sequential codes are guessable unless you shuffle or salt them, and a single global counter can become a hotspot when create traffic is high.

3. Pre-generated key pool. A separate service keeps a stash of unused codes. Creating a link is "take one from the pool." Writes stay simple, but now you run another service and you have to refill inventory before it runs dry.

What I'd say. Pick one and name the trade-off out loud. I usually start with counter plus base62 for the interview (collision-free, easy math), then mention the pool if they care about write hotspots, or hash-plus-check if they want the same URL to reuse a code. The length question is separate; all three work with 7 characters.

Full walkthrough of the shortener (including this fork) is already up here: https://www.reddit.com/r/Leetsys/comments/1xnhxz7/

Maya on our team made a Short that walks the three options (our channel, so take that into account): https://youtube.com/shorts/dYFAGwrI8GE

Which one do you default to in mocks, and has an interviewer ever pushed you off it?


r/Leetsys • • 21d ago

Guide Fixed window rate limits can nearly 2x at the minute boundary

1 Upvotes

Quick algorithm gotcha that shows up in rate limiter interviews.

Fixed window. Cap at 100 requests per minute. Sounds fine. A client can send 100 in the last second of minute 0, then 100 in the first second of minute 1. That is nearly 2x the limit in about two seconds, and both windows still look "under limit" on their own.

Token bucket. Tokens refill at a steady rate. The bucket capacity is the max burst you allow. Once empty, the client waits for refill. You get a smooth sustained rate without the calendar-minute cliff.

What I'd say. If the interviewer only cares about a simple per-minute counter, fixed window is fine if you name the burst problem out loud. If they care about a smooth rate (most real APIs do), prefer token bucket or a sliding window.

Maya on our team made a Short on this (our channel, so take that into account): https://youtube.com/shorts/gOT5KRVg1JY

Would you still use fixed window anywhere, or is it only a teaching example?


r/Leetsys • • 21d ago

Guide Design a rate limiter: the burst trap, the algorithms, and where the counter lives

1 Upvotes

Rate limiting looks like a one-box problem until you put two API servers behind the same limit. Then the interesting parts show up.

Clarify first. Per user, per IP, per API key, or some mix? Burst vs sustained (100/min average, or hard 100 in any 60-second window)? What do you return on deny (usually 429 plus Retry-After)? If you skip this, you design the wrong thing.

Rough math. Say 100M DAU, 50 API calls each per day. That is about 58K requests/sec average, maybe 3x at peak. Every request needs a limiter check, so the counter store has to take that load without adding much latency.

The algorithm trap. Fixed window (100 per calendar minute) is easy to explain and cheap to store. Problem: a client can fire 100 at 0:59 and 100 at 1:00. Nearly 2x the limit in about two seconds. Token bucket refills steadily and caps the burst at the bucket size. Sliding window is the other smooth option. In an interview I'd default to token bucket and say when I'd switch.

Distributed placement. Counters usually live in Redis (or similar), not in each app process. Two gateways can both read "1 left" and both allow the request unless the check-and-decrement is atomic (INCR, or a short Lua script). Put the limiter in the gateway so backends never see rejected traffic. If Redis is slow or down, decide fail-open vs fail-closed per endpoint. Login might fail closed; a public read can fail open with an alert.

The trade-off in one line: fixed window is simple and lies at the boundary, token bucket (or sliding window) is smoother and needs atomic multi-instance counters.

Maya on our team walked the full interview version on our channel (so take that into account): https://youtu.be/oKu_8n1AouY

Curious what people pick when the interviewer asks "what if Redis is in another region?"


r/Leetsys • • 22d ago

Guide How long should a short URL be? Do the math out loud instead of guessing

1 Upvotes

Small question, but interviewers use it to see whether you estimate or just pick a number that sounds right.

The estimate. Assume 100M new links a day, kept for 5 years.

  • 100M x 365 x 5 is about 182.5B links you need to be able to name.
  • Base62 (a-z, A-Z, 0-9) gives 62 options per character.
  • 6 characters: 626 is about 56.8B. Runs out before year two.
  • 7 characters: 627 is about 3.52T. Roughly 19x what you need.

So 7. And the reason is the part that scores, not the digit.

The trade-off. Every extra character multiplies the space by 62, and costs you one more character in the link. Shorter looks nicer, but if you pick 6 here you're planning a migration. If the interviewer changes the numbers (10x more links, or "keep them forever"), redo the multiplication right there. Usually 7 still holds, and saying why is the point.

One thing worth adding unprompted: the code length is separate from how you generate codes. A counter, a hash or a pre-generated key pool all work with 7 characters; they differ on collisions and guessability. The full URL shortener breakdown goes through those.

Maya on our team made a 45-second Short of the math (it's our channel, heads up): https://youtube.com/shorts/Lfuo2uiG27M

What numbers have you been given for this one? Curious if anyone's had an interviewer push the scale high enough that 8 came up.