← All topics

System design

Designing large systems: caching, queues, scaling.

200 questions

Start ▶
Level:
1 What do interviewers actually expect from you in a system design interview? Not a ready-made "right answer" but a way of thinking: clarify the requirements, estimate the load roughly, start with a simple diagram, then strengthen the weak spots and name the cost of each choice. Junior 2 What is the difference between functional and non-functional requirements? Give an example. A functional requirement says what the system does (a user sends a message, places an order). A non-functional requirement says how well it does it: speed, availability, security, how much load it can take. Junior 3 What are latency and throughput, and how are they related? Latency is how long a single request takes (for example, 120 ms). Throughput is how many requests the system can handle per unit of time (for example, 5000 RPS). Improving one doesn't automatically improve the other. Junior 4 What is the difference between vertical scaling and horizontal scaling? Vertical scaling means making one server more powerful (more CPU, RAM). Horizontal scaling means running several identical servers and splitting the load between them. Junior 5 What does a load balancer do, and what happens without one? A load balancer distributes incoming requests across several server instances and doesn't send traffic to a dead one. Without it, one server gets overloaded, or when it goes down the whole service goes down. Junior 6 How do round robin and least connections differ? Round robin hands requests to servers in turn: 1, 2, 3, 1, 2, 3. Least connections picks the server with the fewest open connections right now — which is fairer when requests differ in weight. Junior 7 How does a load balancer know a server is alive, and what happens if the health check is written wrong? The load balancer regularly sends a check request to each server (for example, GET /actuator/health). If there is no answer several times in a row, it takes the server out of rotation. A badly written health check can pull a healthy server out or keep a dead one in. Junior 8 What does a stateless service mean, and why is it easy to scale? A stateless service keeps nothing about the user in its own memory between requests — the state it needs lives in the database, in Redis or inside a token. So any request can land on any instance, and you can add or remove instances freely. Junior 9 What is a sticky session and what are its drawbacks? A sticky session means the load balancer always sends all requests from one user to the same server (usually based on a cookie). It lets you keep the session in server memory, but the load becomes uneven, and if the server dies, its users lose their sessions. Junior 10 At which layers can a system have a cache? At every step from the user to the database: browser cache, CDN, reverse proxy, a local in-process cache, a shared cache like Redis, and the database's own buffer cache. The closer to the user, the faster, but the harder to control. Junior 11 What is the cache hit ratio, and what do you check when it is low? The hit ratio shows what fraction of requests were answered from the cache: hit / (hit + miss). At 95%, only 5% of requests go to the database. When it's low, usually the TTL is too short, the key is built wrong, or the cache is too small. Junior 12 Why does a cache need a TTL, and how do you choose one? The TTL is how long an entry lives in the cache. It puts a limit on how long stale data can be visible, and it keeps unneeded entries from occupying memory forever. Junior 13 How does the cache-aside pattern work? The application looks in the cache first. If it finds the entry, it returns it. If not, it reads from the database, writes the result to the cache and returns it. When the data changes, it writes to the database and deletes the key from the cache. Junior 14 When the cache is full, which entry gets evicted — what are LRU and LFU? A cache has limited size, and when it fills up, something is evicted according to the eviction policy. LRU evicts the entry that hasn't been accessed for the longest time, LFU evicts the entry accessed least often. Junior 15 What is a CDN, and what content should be served through it? A CDN is a network of servers spread around the world that serves content from the point closest to the user. Mostly static things: images, video, JS/CSS, fonts, downloadable files. Junior 16 What are the benefits of database replication? Replication means keeping copies of the same data on several servers. If the main server goes down, you can put a replica in its place, and you can split read requests across replicas to take load off the main server. Junior 17 In a leader-follower setup, where do write and read requests go? All writes go only to the leader (primary), which passes the changes on to the followers. Reads can also be served from followers, but you have to keep in mind that they can be a little behind. Junior 18 What is sharding, and how does it differ from replication? Sharding splits the data into pieces and puts each piece on a separate server — each server stores only part of the data. In replication, every server holds a full copy of all the data. Junior 19 How much downtime do "99.9% availability" and "99.99% availability" mean in practice? 99.9% is about 8 hours 45 minutes of downtime per year, 43 minutes per month. 99.99% is 52 minutes per year, around 4 minutes per month. Each extra "nine" multiplies cost and complexity several times over. Junior 20 What is a single point of failure? Give an example from a simple web application. A single point of failure is a part of the system whose failure stops the whole system. A database on a single server, a single load balancer, a single DNS provider, or a password only one person knows are all examples. Junior 21 What does a message queue give a system? A queue decouples the sender from the receiver: the sender drops off the message and leaves, and the worker picks it up at its own pace. This smooths out load spikes, takes slow work out of the main request, and keeps one service going down from taking another with it. Junior 22 When is synchronous communication between services the right choice, and when asynchronous? Synchronous (REST, gRPC) fits when you need the answer right away: "what is the product's price?". Asynchronous (queue, event) fits when you don't have to wait for the result or the work takes long: sending an email, generating a report, processing a video. Junior 23 Why do you need rate limiting, and where do you put it? Rate limiting caps how many requests one client can send in a given time, for example 100 per minute. It protects the service from abuse, brute force and accidental infinite loops. Junior 24 What should a client do when the server returns 429 or 503? It shouldn't retry immediately. If there is a Retry-After header, it waits that long; if not, it retries with a growing wait on each attempt (exponential backoff) plus random jitter, and caps the number of attempts. Junior 25 Estimate roughly how many requests per second this requirement produces. 10 million requests a day is about 115 RPS on average. At peak that is usually 2–5 times higher, so you should design the system for 300–600 RPS. Junior 26 Estimate roughly how much disk an image storage service needs for 5 years. 2 million images a day × 500 KB is about 1 TB a day, ~365 TB a year, ~1.8 PB in 5 years. Add replication and the small-size copies and it's 2–3 times more — a volume like that only makes sense in object storage. Junior 27 How do you choose between a relational database and NoSQL for a new project? If the data is interconnected and you need transactions and complex queries, use a relational database like PostgreSQL. If you need a huge volume, simple key-based access and easy horizontal scaling, use NoSQL. For most projects, a relational database is the default choice. Junior 28 What is an API gateway, and how does it differ from a plain load balancer? An API gateway is the single entry point for all external requests. Besides routing a request to the right service, it also handles shared concerns like authentication, rate limiting and logging. A load balancer mainly distributes traffic among the instances of one service. Junior 29 What happens at the system level when you type a site address into the browser and press Enter? First DNS turns the domain name into an IP address, then comes the TCP connection and TLS handshake, then the HTTP request reaches the application server through a CDN or load balancer. The application hits the cache and database if needed and returns a response, and the browser renders the page. Junior 30 For a new startup, is it better to start with a monolith or go straight to microservices? Starting with a monolith is usually right: the team is small, the domain isn't clear yet, and you need to change things fast. Microservices pay off when large teams need to deploy independently and parts of the system need to scale separately. Junior 31 What is the difference between a reverse proxy and a forward proxy? A forward proxy sits on the client side and goes out to the internet on behalf of clients — the server doesn't see the real client. A reverse proxy sits on the server side and accepts requests on behalf of servers — the client doesn't see the real servers behind it. Junior 32 What is an idempotent operation, and why is it required in a payment API? Running an idempotent operation once or five times gives the same result. In a payment, if the network drops, the client resends — and if the operation isn't idempotent, the customer is charged twice. Junior 33 How can you generate the short code in a URL shortener? The simplest way is to convert the database auto-increment ID to base62: 125 → "21". Other options are to generate a random code and check for collisions, or to hash the URL and take the first characters. Junior 34 How many unique links does a 7-character base62 code hold, and is that enough? 62⁷ ≈ 3.5 trillion combinations. Even at 100 million new links a day, that lasts more than 90 years. 6 characters give ~57 billion — enough for a smaller service. Junior 35 Compare polling, long polling and WebSocket for delivering a new message to the client in a chat app. With polling, the client asks every few seconds "any new messages?". With long polling, the request stays open until a message appears. A WebSocket is one persistent two-way connection, and the server pushes the message right away. For chat you usually pick WebSocket. Junior 36 Why should sending notifications (SMS, email, push) be split off from the main request and made asynchronous? External providers are slow and unreliable: an SMS gateway can take 3 seconds to respond or return an error. If you put the notification on a queue and send it through a separate worker, the main operation finishes fast and retrying on failure is easy. Junior 37 Why should you store user-uploaded images and videos in object storage rather than in the database? Large binary files bloat the database: backups and replication slow down, and memory and disk get expensive. Object storage (S3, MinIO) is built exactly for large files: it's cheap, scales without limit and plugs into a CDN easily. The database keeps only the file key and metadata. Junior 38 Why do feed pages use cursor pagination instead of offset pagination? With offset, when a new post is added the pages shift — the user sees one post twice or skips one. On top of that, a large OFFSET is slow. Cursor pagination says "give me the posts after this one": the result is stable and every page is equally fast. Junior 39 Which metrics do you collect first to monitor a service in production? Four main signals: latency (response time, especially p95/p99), traffic (RPS), errors (the share of failures) and saturation (how full the CPU, memory and connection pool are). These show most problems. Junior 40 What happens if you don't set a timeout on every call to an external service? If the external service stops responding, your threads wait forever. The thread pool and connection pool slowly fill up, and in the end your service can't answer even requests that have nothing to do with it. Junior 41 An admin changed a product's price, but the site still shows the old price for 10 minutes. What's the cause and how do you fix it? The price sits in the cache with a TTL and the key wasn't evicted on update. The fix is to evict the exact key after the write, to account for every cache layer if there are several (local + Redis + CDN), and to shorten the TTL for important data like prices. Strong Junior 42 A user saved their profile and the page reloaded, but the old name is shown. A few seconds later everything is fine. What's happening? This is replication lag: the write went to the primary, but the read was served by a replica that hasn't caught up yet. The fix is a read-your-writes guarantee: for a short time after a change, send that user's reads to the primary. Strong Junior 43 Explain the CAP theorem in plain words. What does it mean in practice? In a distributed system, when the network splits (a partition), you have to pick one of two: either you always give correct data and reject some requests (consistency), or you answer everyone but some answers may be stale (availability). Strong Junior 44 What is the difference between strong consistency and eventual consistency, and which one fits which feature? With strong consistency, every read sees the new value the moment a write finishes. With eventual consistency, copies may differ for a while, but if no new writes arrive, they all end up in the same state. Strong Junior 45 What is wrong with the following retry code, and what could it cause in production? The code retries without waiting, without limit and on any error. When the service slows down, all clients pile on at once and multiply the load several times over, taking it down completely (a retry storm). You need a capped number of attempts, exponential backoff + jitter, and retries only on transient errors. Strong Junior 46 What is the downside of sharding data with the `userId % N` formula? When the shard count changes, almost all keys move to a different shard: going from 4 to 5, you have to move about 80% of the data. Consistent hashing, or splitting into many virtual buckets up front, reduces this problem. Strong Junior 47 If the same message arrives twice from a queue, how do you protect the worker? Most brokers give an at-least-once guarantee, so duplicates are normal. You need to make the worker idempotent: store each message's unique ID and don't redo one that was already handled, or write the operation itself so that repeating it is harmless. Strong Junior 48 When a popular key's cache entry expired, thousands of requests suddenly hit the database. What is this called, and how do you protect against it? This is a cache stampede (thundering herd): the moment the key dies, all parallel requests get a miss and go to the database at the same time. The protection is to let one request reload the value while the others wait (a lock or request coalescing), add jitter to the TTL, and refresh in the background before expiry. Strong Junior 49 How does the token bucket algorithm work, and why is it so widely used for rate limiting? Each client has a "bucket": tokens are added to it at a steady rate (for example, 10 per second), and its capacity is limited (for example, 50). Each request takes one token, and if there are none, it is rejected. This limits the average rate but allows short bursts. Strong Junior 50 Where does a single user with millions of followers cause problems in a social network? They become a "hot key": their profile and posts overload one shard or one cache node, and each new post has to be written into millions of feeds. Accounts like this need a special path — merging their posts at read time, replicating the key, and a local cache. Strong Junior 51 A server's IP address changed, but some users are still going to the old server. How does the DNS TTL relate to this? A DNS answer is cached by resolvers, the OS and the browser for the length of the TTL. With a TTL of 1 day, some users keep going to the old IP for up to a day after the move, so you need to lower the TTL ahead of time, before the migration. Strong Junior 52 The database has a replica. Why do you still need a separate backup? A replica copies a mistake just as fast: if someone sends a DELETE without a WHERE, the rows vanish on the replica a second later too. A backup keeps the state at a given point in time, so you can roll back to a moment before the mistake. Strong Junior 53 If lots of requests come in for IDs that don't exist in the database, why doesn't the cache help, and what do you do? This is cache penetration: a missing key never gets into the cache, so every request goes straight to the DB. The fix is to cache the "not found" answer too with a short TTL, validate the ID format, and use a Bloom filter if needed. Strong Junior 54 When you scale service instances from 2 to 10, why does the DB start throwing "too many connections" errors? Each instance has its own connection pool, so the total number of connections is multiplied by the number of instances. 10 × 50 = 500 connections can exceed the DB limit. Strong Junior 55 Generating a report takes 2–3 minutes. How do you design the API for a long operation like that? The request immediately returns 202 Accepted and a job ID, and the work runs in the background. The client polls the status with GET /jobs/{id} or gets a webhook/notification when it's done, and the result is downloaded through a separate link. Strong Junior 56 What is the difference between a local cache (for example Caffeine) and a distributed cache like Redis, and when do you pick each? A local cache lives in the application's memory — very fast, no network, but every instance has its own copy and they don't know about each other. Redis is one for all instances and invalidation is easy, but every read goes over the network. Strong Junior 57 What is the difference between pub/sub (a topic) and a point-to-point queue? In a queue, only one consumer gets each message — it's for splitting work among workers. In pub/sub, every subscriber gets its own copy of the message — so several services can process the same event independently. Strong Junior 58 What is the difference between blue-green and canary deploys, and which one exposes fewer users to a bug? In blue-green, the new version is brought up in full alongside the old one and traffic switches over all at once, and rolling back is instant too. In canary, a small share of traffic (say 5%) goes to the new version, and if the metrics look good, it is gradually increased. Strong Junior 59 What is the difference between batch processing and stream processing, and when do you need which? Batch collects data and processes it all at once at a set time (for example, every night). Stream processes each event as it arrives. Where the result can wait hours, batch is simpler; if you need it in seconds, use stream. Strong Junior 60 What is the difference between availability and durability? Availability is whether the system can answer requests right now. Durability is whether written data won't be lost. A service can be down for an hour, but if the data stays intact, durability hasn't been broken. Strong Junior 61 Estimate roughly how much memory a Redis cache for a product catalog needs. Start from the number of unique objects read per day and the size of one object; by the 80/20 rule you cache the hot 20%. Then add Redis's per-key and structure overhead, plus headroom for replicas and growth. Middle 62 What is the difference between the cache-aside, write-through and write-behind approaches? In cache-aside, the application reads from the cache itself, and on a miss fetches from the DB and puts it in the cache. In write-through, the write goes synchronously through the cache to the DB. In write-behind, the cache accepts the write and writes to the DB later, asynchronously. Middle 63 What is service discovery, and how do client-side and server-side discovery differ? Service discovery is how a service finds out the addresses of another service's currently running instances. In client-side discovery, the client gets the list from a registry and balances itself; in server-side discovery, the client goes to a single address (an LB or a Kubernetes Service) and that makes the choice. Middle 64 What is the difference between an L4 and an L7 load balancer? An L4 balancer works at the TCP/UDP level: it sees only the IP and port and doesn't look inside the packet. An L7 balancer understands HTTP: it routes by URL, header or cookie and terminates TLS, but uses more resources. Middle 65 For calls between internal services, when is it worth moving from REST/JSON to gRPC? gRPC gives you binary Protobuf, HTTP/2 multiplexing and a strict contract — faster and safer for lots of small internal calls. But it doesn't work with browsers directly and is harder to debug, so the external API usually stays REST. Middle 66 How do the token bucket and fixed window algorithms differ in rate limiting? Fixed window keeps a counter for each time interval (for example, a minute) and can let through double the load at the boundary. Token bucket refills tokens evenly, allows short bursts, but holds the average rate firmly. Middle 67 Your service runs on 6 instances. How do you enforce a limit of 60 requests per minute per user? The counter must be kept in a shared place, usually Redis, not in each instance's memory, and the check-and-increment must be atomic: INCR + EXPIRE or a Lua script. Middle 68 How do you count likes and views on posts when tens of thousands of writes per second come in? UPDATE posts SET likes = likes + 1 for every like chokes a single row on its lock. You need to accumulate the counter in Redis with INCR, or in a sharded counter split into several pieces, and write to the DB in batches; the like itself is stored in a separate table with a unique key. Middle 69 What is CQRS, and when does separating the read model from the write model pay off? CQRS means separate models for writes (commands) and reads (queries), sometimes separate databases. The write model holds the business rules, while the read model is denormalized and ready for the screen. It pays off when the shape of reads and writes differ a lot. Middle 70 How do you build the "online" / "last seen" status for users in a chat app? The client sends a heartbeat on connect and every N seconds, and the server stores the user's status in Redis with a TTL. When the TTL expires, they're offline. You should push status changes not to all contacts but only to those who have the screen open right now. Middle 71 You need to choose between Kafka and RabbitMQ. What criteria do you look at? Kafka is a retained, replayable log: for large event streams, event sourcing, and several independent consumer groups. RabbitMQ is a classic queue: handy for complex routing, per-message acks and distributing jobs to workers. Middle 72 Design a notification service that sends email, SMS and push. What are the main components? Other services send events, and the notification service builds the message based on user preferences and a template, puts it on separate queues per channel, and workers send it to the providers with retries and record the result. Middle 73 A user uploads a large file (video, image). How do you accept it without passing the file through the backend? The backend creates a short-lived presigned URL for object storage (S3 or MinIO), the client uploads the file straight to the storage, and then tells the backend "uploaded". The backend's threads and network don't carry the file. Middle 74 What is the difference between synchronous and asynchronous replication, and which one can lose data? With synchronous replication, the primary says "committed" only after a replica confirms the write — nothing is lost, but writes are slower. With asynchronous, the primary answers right away and the replica catches up later — if the primary dies, the last few transactions can be lost. Middle 75 What problems come up if the sharding key is chosen badly? Data and load spread unevenly — one "hot" shard fills up while the others sit empty. Another problem: many queries fan out to all shards (scatter-gather) and get slow. Middle 76 Denormalization — duplicating data to speed up reads: when is it right, and what does it cost? If a heavily read page does a heavy join every time, copying the needed fields in advance (for example, the customer name on the order, the comment count on the post) makes reads cheaper. The cost is that writes get more complicated and the copies can drift out of sync. Middle 77 What happens to this `@Scheduled` method when the service runs on 3 instances, and how do you fix it? Each instance runs its own scheduler, so the job runs 3 times — customers get 3 emails. The fix is a distributed lock (for example, ShedLock with a DB table), moving the job to a single dedicated worker, or making the work idempotent. Middle 78 Data has grown over the years and a table has become huge. How do you archive old data (hot/cold)? Recent, actively used data stays in the fast database, while old records are moved to cheaper storage (a separate table, a partition or object storage). Partitioning by time turns moving and deleting into a single DETACH/DROP. Middle 79 How do you generate unique IDs in a system with several services and databases: UUID, a DB sequence or Snowflake? A DB sequence is simple and compact, but ties everything to the DB. A UUID depends on nobody, but because it's 128 bits and random it bloats the B-tree index. A 64-bit Snowflake-style ID sorts by time and is generated without central coordination. Middle 80 When is `LIKE '%...%'` not enough for searching products by name, and you need a search system like Elasticsearch? LIKE '%word%' can't use a plain B-tree index and does a full scan on a large table; there's also no morphology, no typo tolerance and no sorting by relevance. If you need those, you use a full-text search system. Middle 81 How does consistent hashing work, and why do you need virtual nodes? Servers and keys are both hashed onto one ring, and a key belongs to the first server clockwise from it. When a server is added or removed, only the keys in the neighboring range move. Virtual nodes spread the load more evenly. Strong Middle 82 The Redis cache cluster suddenly went down and the DB started collapsing under the load. How do you protect against that in advance? While the cache works, the DB sees only a small share of "misses"; when the cache goes down, the entire read load hits the DB. Protection: replicas and failover for the cache, a local cache layer inside the application, limiting requests that go to the DB, and warming the cache up step by step on recovery. Strong Middle 83 One very popular key (a hot key) overloaded a Redis node. How do you detect it and what do you do? Adding nodes to the cluster doesn't help, because a hot key lands on one shard. To detect it, you look at redis-cli --hotkeys or client metrics; the fixes are a local cache, splitting the key into several copies, or making the value smaller. Strong Middle 84 In this code, in what situation does a stale value stay between the cache and the DB for a long time? There's a race between two requests: a reader fetched the old value from the DB, meanwhile the writer updated the DB and evicted the cache, and then the reader put the old value into the cache. Now the stale value stays until the TTL expires. Strong Middle 85 How do you make saving an order to the DB and sending an event to Kafka a single atomic unit? You can't write to two different systems in one transaction. With the outbox pattern, the event is written to an outbox table in the same DB transaction as the order, and a separate relay reads it and sends it to Kafka. Strong Middle 86 Design a chat application where users message each other: connections, message delivery and offline users. Clients connect to gateway servers over WebSocket, and Redis stores which user is on which server. A message is first written to the DB and gets an ID, then sent to the recipient's server; if they're offline a push notification goes out, and when the client reconnects it asks for the history starting from the last ID it saw. Strong Middle 87 What is the difference between fan-out on write and fan-out on read when building a news feed? How do you handle a user with millions of followers? With fan-out on write, a post is added to each follower's ready-made feed when it's written — reads are fast, writes are expensive. With fan-out on read, the posts of the people you follow are gathered when the feed is opened — writes are cheap, reads are heavy. In practice it's a hybrid: write for ordinary users, read for "stars". Strong Middle 88 In a payment service, a client got a timeout and resent the request. How do you guarantee the money isn't charged twice? For each payment attempt the client sends an idempotency key, and the server stores it with a unique constraint and records the result. A repeated request doesn't open a new payment — it returns the stored result, or 409 if the first one hasn't finished yet. Strong Middle 89 How do the circuit breaker's states work, and what problems come up if it's configured wrong? In the closed state calls go through and failures are counted; if the failure rate goes above the threshold, the breaker opens and rejects calls immediately; after a set time, in half-open a few trial requests are let through, and depending on the result it closes again or opens. Strong Middle 90 Kafka consumer lag has been growing for hours. What do you check and how do you fix it? First I establish the cause: did the events increase, or did processing slow down. Then I look at processing time, rebalances, the number of partitions and consumers, and external calls. The usual fixes are fixing the slow spot, batching, and adding partitions and consumers. Strong Middle 91 How does split brain occur during automatic failover in leader-follower replication, and how do you prevent it? When the network splits, the old leader stays alive but the others consider it dead and elect a new leader — two nodes accept writes at the same time and the data diverges. To prevent it you need a quorum-based election, shutting down the old leader (fencing), and accepting writes only when a majority confirms them. Strong Middle 92 What do the N, W and R parameters mean in leaderless replication, and what does the W + R > N condition guarantee? N is the number of copies of each key, W is the number of copies that must confirm a write before it's called successful, R is the number of copies that must answer a read. If W + R > N, the read and write sets overlap in at least one copy, and the read sees the last confirmed write. Strong Middle 93 The data is on 4 shards and now you need 8. How do you plan the redistribution without stopping the service? You have to copy the data, catch up in the background, and then move reads and writes to the new place step by step. The easiest way is to start with many logical shards (for example, 256) and move them whole between physical servers. Strong Middle 94 What are the risks of a distributed lock built on Redis, and why do you need a fencing token? The lock is taken with a TTL; if the owner freezes for longer than the TTL because of a GC pause or the network, the lock passes to someone else and two processes work at the same time, both believing "I'm the owner". A fencing token is an increasing number issued with each lock; the resource rejects writes with an older number. Strong Middle 95 How do you write a sliding window log rate limiter in Redis, and why should it be done with a Lua script? For each user, the request times are stored in a sorted set: entries older than the window are removed, the rest are counted, and if the count is below the limit the new time is added. These steps must be atomic, otherwise parallel requests slip past the limit. Strong Middle 96 What happens in a system if the producer sends data faster than the consumer can take it, and how do you apply backpressure? A buffer or queue in between grows without limit — memory runs out, latency rises, and in the end something falls over. Backpressure means the slow side signals the fast side to "slow down": a bounded queue, blocking, rejecting, or pulling on demand. Strong Middle 97 What is a poison message, and how does a dead letter queue handle it? A poison message is one that makes the consumer fail every time (broken JSON, an ID that isn't in the database). It blocks the queue with endless retries. After a few attempts you need to move it to a dead letter queue and carry on with the other messages. Strong Middle 98 After updating the JS and CSS files on the CDN, users see the old version. How do you set this up properly? Put a content hash in the file name (app.3f9a1c.js) and cache those files for a long time; serve the HTML for a short time or with revalidation. A new deploy means a new name, so no invalidation is needed. Strong Middle 99 A product page gets data from 6 services. What do you do so the page still opens when the recommendations or reviews service goes down? You split each dependency into required and optional. The optional ones are called with a short timeout, a circuit breaker and a fallback (an empty block, stale data from the cache), and in parallel; if the required part (price, stock) is missing, you return an explicit error. Strong Middle 100 Orders, payments and inventory are separate services. How do you build the process across them with a saga, and what is the difference between orchestration and choreography? A saga is a chain of local transactions in each service; if a step fails, the earlier ones are undone with compensating actions. In choreography, services react to each other's events on their own; in orchestration, a central coordinator commands every step. Strong Middle 101 What is a Bloom filter, and where does it give real benefit in system design? A Bloom filter is a compact structure made of a bit array and several hash functions: it answers "definitely not there" or "probably there". There are no false negatives, and false positives occur at a tunable rate, so it is used as a cheap filter in front of an expensive check. Strong Middle 102 A site gets billions of views a day. How do you count the unique visitors of each page without blowing up memory? Storing every user ID in a Set takes too much memory. HyperLogLog estimates the number of unique elements in about 12 KB of memory with ~0.8% error; Redis has it built in with PFADD/PFCOUNT, and you can merge different days with PFMERGE. Strong Middle 103 What is wrong with this update order in cache-aside? Updating the cache and writing to the DB aren't atomic: with two parallel writes, a stale value stays in the cache. Usually you write to the DB first and then delete the cache key (delete, not update), and a short TTL covers the remaining cases. Strong Middle 104 How do you compute the 100 most viewed products (top-K) over the last hour in real time? At small volume, ZINCRBY on Redis sorted sets per time slice, then merging several slices with ZUNIONSTORE, is enough. On a very large stream you need approximate structures like a count-min sketch inside stream processing, plus two-stage aggregation. Strong Middle 105 For authentication, how do you choose between JWT (stateless) and a server-side session, and what do you do if you need to log a user out immediately? Every service checks a JWT without going to the DB — scaling is easy, but you can't revoke a token before it expires. A session is stored centrally and deleted instantly, but every request needs a trip to the store. In practice a short access token is combined with a refresh token stored on the server. Strong Middle 106 How do the token bucket and sliding window rate limiter algorithms differ, and when do you pick which? Token bucket allows short bursts and limits the average rate. Sliding window enforces an exact "M requests in the last N seconds" rule. For an API it's often token bucket; for a strict quota (for example, login attempts), sliding window. Strong Middle 107 Why are LSM-tree databases like Cassandra or RocksDB very fast at writes but sometimes slow at reads? An LSM-tree first appends a write to the WAL and an in-memory memtable, then flushes it to sorted files (SSTables) — only sequential writes reach the disk. On reads, a key may be in several files; Bloom filters and compaction soften this, but compaction itself eats disk and CPU. Strong Middle 108 How much data should you put in an event: just an ID (notification event) or the full state (event-carried state transfer)? If you send only the ID, the event is small, but every consumer goes back to the producer to get the data — the dependency and the load come back. If you send the full state, consumers are independent, but the event is big and the schema becomes a contract. The choice depends on the number of consumers and how fast the data goes stale. Strong Middle 109 What is log compaction in Kafka, and which topics would you make compacted? In a compacted topic, Kafka keeps at least the last value for each key and cleans out older versions in the background. It's meant for data like "the current state of each entity": a new consumer can read the topic from the start and rebuild the full state, while the topic doesn't grow forever. Strong Middle 110 How do you choose the partition key for a Kafka topic, and what problems does a wrong choice cause? You choose it by the unit that needs ordering — usually orderId or userId, since order is guaranteed only within a partition. If the key has few distinct values or is skewed, one partition overheats and the consumer falls behind. Strong Middle 111 In one queue, VIP customers' orders are stuck behind regular orders. How do you organize priority? The most reliable way is separate queues by priority, with dedicated or more workers for them. Priority inside a single queue (a RabbitMQ priority queue) works at small volume, but you also have to account for low-priority work "starving". Strong Middle 112 A payment provider sends the result through a webhook. How do you build the receiving side reliably? Accept the webhook quickly (verify the signature, store it, return 200) and do the processing asynchronously. The provider can resend and reorder events, so you also need dedup by event ID, a state machine, and a periodic check by asking the provider for the status (polling). Strong Middle 113 How do you design a web crawler: which page to fetch when, how not to overload sites, and how to avoid duplicates? The core is the URL frontier: a queue grouped by domain, with a per-domain rate limit (politeness) and respect for robots.txt. Seen URLs go in a Bloom filter or hash set, content duplicates are detected with a hash/simhash, and the fetcher, parser and storage scale separately. Strong Middle 114 Should a URL shortener return 301 or 302 for the redirect? A 301 is cached by the browser and later clicks never reach the server — less load, but you lose statistics and can't change the target. If you need to count clicks or edit the link, use 302 (or 307). Strong Middle 115 In a chat application, users are connected to different servers over WebSocket. How does A's message reach the server B is connected to? You need a registry that stores who is connected to which server (for example, Redis) and a message channel between servers (Redis Pub/Sub, Kafka or direct gRPC). The message is first written to the DB, then routed to B's server. Strong Middle 116 In a group chat, how do you maintain message order and the "delivered/read" states? For order, the server assigns a monotonically increasing number (sequence) within each chat; the client's time isn't trusted. The read state is stored not per message but per member, as the "last read sequence". Strong Middle 117 A live stream gets tens of thousands of comments and reactions per second. How do you deliver them to all viewers? Pushing each comment to each viewer separately multiplies the load by the number of viewers. Comments are distributed per stream through Kafka/pub-sub to gateway servers, and each gateway sends to its own connections; reactions are aggregated and delivered as a count every second, and comments are sampled. Strong Middle 118 A mobile app works in offline mode. How do you sync the changes a user made without internet to the server later? The client stores the changes in a local database as a queue of operations and gives each a unique ID; when the connection returns they're sent idempotently. The server detects conflicts by version or updated_at and resolves them with a pre-agreed rule, and the client fetches what changed since its "last sync point". Strong Middle 119 In Kubernetes, which metric do you tie a service's autoscaling to: CPU, request count or queue length? CPU is a good signal only for services that are CPU-bound. For services that wait on I/O, request count or in-flight requests is better, and for workers that read from a queue, queue length or consumer lag is more accurate. And if a downstream dependency (the DB) is limited, scaling can take it down. Strong Middle 120 How can a wrongly configured liveness or readiness probe in Kubernetes take down a whole service? If you check the DB or another service inside liveness, then when the DB slows down all pods restart at once and the service stops on its own. Liveness should check only "is the process alive", and readiness "is it ready to take traffic". Strong Middle 121 During a deploy, a few requests fail with 502. How do you set up graceful shutdown and connection draining correctly? When a pod is being shut down, the LB doesn't remove it from the list instantly, so after SIGTERM the application has to keep accepting traffic for a few seconds and finish the requests in flight. In Spring this is solved with server.shutdown=graceful and a preStop pause. Strong Middle 122 In a hotel booking system, how do you make sure two people can't book the same room for the same day? "Check first, then write" lets both through when two requests run in parallel. The guarantee has to come from the database itself: a unique constraint on (room, date), an exclusion constraint in PostgreSQL, or updating an inventory row with a lock/optimistic version. While payment is pending, use a temporary hold with a TTL. Strong Middle 123 When caching API responses through a CDN, which Cache-Control directives matter, and what mistakes show personal data to other people? s-maxage sets the lifetime for shared caches, max-age for the browser, and private means the CDN must not cache. The most dangerous mistake is marking a user-specific response public, or forgetting Vary. Strong Middle 124 You want to shard the orders table. Which do you pick as the shard key: `user_id`, `order_id` or `created_at`? Pick the key that most queries use — usually user_id: one user's orders sit on one shard, and queries go to one shard. created_at piles all new records onto one shard, and order_id spreads "a user's orders" across all shards. Strong Middle 125 The data is sharded by `user_id`. Now you need to search by another field and join across shards. What do you do? The main routes: a global index table for the secondary key (email -> user_id), moving search to a separate system (Elasticsearch), copying small reference tables to every shard, or, if needed, querying all shards and merging the results. Strong Middle 126 How do nodes in a cluster find out that another one has failed, and what does the gossip protocol give here? Every node periodically passes the state it knows (who is alive, heartbeat counters) to a few random neighbors, and the information spreads across the cluster like an epidemic. No central coordinator is needed; but the conclusion "it's dead" is probabilistic, so a timeout and a "suspect" stage are used. Strong Middle 127 Why can't you determine the order of events in a distributed system with a plain timestamp, and what do a Lamport clock or a vector clock give you? The clocks of different servers differ by milliseconds, sometimes seconds, and can even go backward, so a timestamp doesn't reliably tell you "what happened first". A Lamport clock gives a number consistent with causal order, and a vector clock can also tell whether two events are related or concurrent. Strong Middle 128 What odd situations does a user see in a system with eventual consistency, and how do you soften them? The most common: not seeing what you just wrote, data "going backward" when you refresh the page (a monotonic reads violation), and seeing the answer before the question (a causal order violation). You soften them with session-bound guarantees. Strong Middle 129 What does this balance update code break with parallel requests, and how do you fix it? The code reads the value, changes it in Java and writes it back — two parallel requests read the same old balance and one overwrites the other's result (a lost update). The fix is an atomic UPDATE ... SET balance = balance - ? WHERE balance >= ?, an optimistic version, or SELECT ... FOR UPDATE. Strong Middle 130 How do you design an audit log system: reliably storing and searching who changed what, and when? Audit records are stored in an append-only place that can't be modified, and written in the same transaction as the business change or through an outbox. To avoid slowing down the main request, they are moved asynchronously into a separate store built for search, and immutability is enforced with permissions and a hash chain. Strong Middle 131 Estimate how many application instances and how many DB connections are needed for the following figures. By Little's law, the number of concurrent requests = RPS × average response time. At peak, 3000 RPS and 200 ms give ~600 concurrent requests; if each pod handles ~100, that's ~8–10 pods with headroom. DB connections are far fewer, depending on the time spent in the DB. Strong Middle 132 What do feature flags give you in system design, and how do they turn into a source of risk? A feature flag separates deploy from release: the code is on prod, but the feature is switched on with a flag — by percentage, by segment, and turned off instantly if there's a problem. The risks are that stale flags clutter the code, combinations go untested, and the flag service itself becomes a critical dependency. Strong Middle 133 What is deadline propagation, and why is it a problem when each service sets its own timeout independent of the chain? A user request has an overall time limit (a deadline), and it is passed to each following call as the "remaining time". If each service waits 5 seconds on its own, work inside keeps going for a request the outer client has already given up on — wasting resources, and under load that chokes the system. Strong Middle 134 What is the bulkhead pattern, and how does it protect against one slow dependency stopping the whole application? A bulkhead isolates resources (thread pools, connections, semaphores) separately for each dependency or kind of work. If one fills up, only that part rejects requests, and the rest keep working. Strong Middle 135 How do you build a real-time leaderboard with millions of players? A Redis sorted set (ZADD, ZINCRBY, ZREVRANGE, ZREVRANK) is almost ready-made for this: adding points and finding a rank is O(log N). The source of truth stays in the DB, and Redis serves fast reads; at very large volume you split the leaderboard into pieces or give ranks approximately. Strong Middle 136 How does a consensus algorithm like Raft work, and why does a cluster usually have 3 or 5 nodes? In Raft, one leader appends writes to its log and sends them to the followers; once a majority (a quorum) confirms a write, it's committed. Thanks to the majority rule, 3 nodes survive one failure and 5 nodes survive two; an even number doesn't add fault tolerance. Strong Middle 137 In a file sync service like Dropbox, what do splitting files into chunks and deduplication give you? A file is split into chunks of about 4 MB and each chunk is stored under its hash. When a file changes, only the changed chunks are uploaded, an interrupted upload resumes from where it stopped, and identical chunks are stored once. The file's metadata is the list of chunk hashes, in a separate database. Strong Middle 138 How do you design a system that sends webhooks to customers' servers? Events are written to a queue, and workers deliver them separately for each customer: with a signature (HMAC), a short timeout, retries with exponential backoff over several days, and a stored delivery history the customer can view. Strong Middle 139 How do you design an autocomplete (typeahead) service for a search box? Popular queries are computed offline and stored in memory as ready-made top-N lists by prefix (a trie or a prefix -> results map). Each keystroke is a single fast lookup, and the client reduces the number of requests with debounce and a cache. Strong Middle 140 What happens when Redis memory fills up, and how do you choose `maxmemory-policy` for a cache? When it reaches maxmemory, Redis either evicts keys according to the policy or rejects writes with an error. For a pure cache it's usually allkeys-lru or allkeys-lfu; if the Redis holds a mix of cache and important data, use volatile-* or, better, split them into separate instances. Strong Middle 141 How do you build the data model for a wallet and payments system, and why isn't storing the balance in a single column enough? Money movement is stored as immutable double-entry ledger records: each operation is a debit and credit pair that sums to zero. The balance is a number derived from the records (and cached); the payment itself is kept in check by an explicit state machine and regular reconciliation with the provider. Senior 142 A service has to run in two regions. How do you choose between active-passive and active-active? Active-passive is simple: writes go to one region, the other stands by as a replica for failover, but a failover can lose data and cause minutes of downtime. Active-active writes in both regions — better latency and availability, but far more write conflicts and complexity. Senior 143 How do you migrate a large monolith to microservices step by step using the strangler fig approach? A routing layer (gateway/proxy) is placed in front of the monolith, new features and extracted parts are written as new services, and traffic is moved to them route by route; the monolith gradually "withers". The hardest part isn't code but data: splitting the shared database and syncing during the transition. Senior 144 Your service suddenly got 5 times the traffic and started to fall over. How do you make the system degrade gracefully under load with backpressure and load shedding? An overloaded service is better off rejecting the excess immediately than serving every request slowly: bounded queues, a limit on concurrent requests, dropping requests whose deadline has passed, and priority for critical traffic. The load is pushed back to the source (backpressure), which slows down. Senior 145 You need to rename a column or change its type in a table running in production. How do you do it with no downtime and with the ability to roll back? The expand/contract method: first a new column is added, the code writes to both columns, old data is copied in batches, reads switch to the new column, and only at the end is the old column dropped. Each stage is a separate deploy, and at each one the old version of the code can still work. Senior 146 How do you design global rate limiting for a public API running in several regions? Going to a central counter on every request adds cross-region latency to each one. In practice the limit is split between regions, or each region counts locally and periodically syncs the global state; this trades some accuracy for speed. Senior 147 How do you design a job scheduler that runs millions of scheduled tasks (reminders, deferred payments, subscription renewals) at exact times? Tasks are stored in a database indexed by run_at, and several workers pick up the tasks coming due with FOR UPDATE SKIP LOCKED or partitioned ownership and hand them to a queue. Each task is idempotent, with a status and a lease — if a worker dies, the task moves to another one. Senior 148 The business demands "99.99% availability". What does that number mean, and how do you turn it into engineering decisions? 99.99% means ~4.3 minutes of downtime a month, and 99.9% means ~43 minutes. Each additional "nine" raises cost and complexity sharply, so you set SLOs per user flow, compute an error budget, and make decisions (deploy speed, redundancy, multi-region) against that budget. Senior 149 Cache-DB inconsistency is causing regular complaints on prod. Instead of relying on TTL, how do you build invalidation through CDC, and what are its risks? Database changes are read from the WAL/binlog (with something like Debezium) and arrive through Kafka at a cache invalidation service, which deletes the relevant keys. The problem of "forgetting the cache" in application code goes away, but lag, the key mapping and Kafka's reliability become new sources of risk. Senior 150 In a flash sale, 200 thousand people want to order 1000 units of a product within a minute. How do you build the system so you don't oversell or take down the database? Decrementing stock with an UPDATE on a single DB row turns into a lock queue under this load. You count stock atomically in Redis (DECR or Lua), write the successful reservations to the DB through a queue, and reject the excess requests as early as possible — at the edge and the gateway. Senior 151 Someone is guessing passwords against your login endpoint (brute force, credential stuffing). How do you build the rate limiting? A per-IP limit isn't enough: the attack comes from thousands of IPs with one or two attempts per account. I put limits on several dimensions (account, IP, and the overall share of failures) and I slow attackers down and show a CAPTCHA instead of hard-blocking. Senior 152 Write load has reached the capacity of a single Postgres primary. What do you try before sharding? Sharding is a last resort, and it complicates all the code and operations. First I make the writes themselves cheaper: drop unneeded indexes, batch, aggregate frequently updated counters, move log-like data to other storage, then partitioning and separate databases per domain; after that, a bigger machine. Senior 153 What problems does a "big key" in Redis cause (say, a hash with 2 million elements or a 50 MB string), and how do you fix it? Redis runs commands on a single thread, so reading or deleting a big key in full can freeze the whole node for seconds. To find them, use --bigkeys and MEMORY USAGE; to fix it, split the key, read in pieces with HSCAN, and use UNLINK instead of DEL. Senior 154 When read load grows, do you add a read replica or put in a cache? How do you choose? If the queries are varied and the data has to be fresh, a read replica; if the same things are read over and over and a bit of staleness is fine, a cache. You often need both, but each one has a different cost. Senior 155 IoT devices send 100 thousand measurements per second. How do you store them, and how do you make a "last 30 days chart" query fast? This is time-series data: append-only, read by time range, and the old data matters less. Kafka as a buffer at ingestion, a time-partitioned columnar or time-series database for storage, and for charts precomputed minute and hour aggregates plus a retention policy. Senior 156 One of the pods got slow (GC, a noisy neighbor), but the load balancer still sends it an equal share of traffic. Which balancing handles this better? Round robin doesn't know the state of the backend. Least request, especially power of two choices (pick two random backends and take the less busy one), and latency-aware EWMA send less to a slow pod on their own; outlier detection temporarily ejects the bad one. Senior 157 Old versions of a mobile app stay in use for years. How do you evolve the backend API without breaking them? You can't force a mobile client to update, so API changes must be additive only: add a new field, never remove an old one or change its meaning. For a breaking change you need a version, monitoring of old-version traffic, and a minimum-version mechanism. Senior 158 To show "Total: 12,345,678 results" on a big table, `COUNT(*)` takes seconds on every page. How do you fix it? In Postgres, COUNT(*) really counts the matching rows because of MVCC, and on a big table that won't be fast. Usually you don't need the exact number: an estimate from statistics or EXPLAIN, a "1000+" cap, LIMIT n+1 for "is there a next page", or a counter maintained ahead of time is enough. Senior 159 When a dependency slows down, retries bring the whole system down. How do you prevent it? Retries multiply load: if each layer retries 3 times, one request becomes 27 across 3 layers. Short timeouts, exponential backoff with jitter, a retry budget and a circuit breaker have to work together. Senior 160 A video streaming service has 1 million concurrent viewers. Estimate the CDN egress traffic and the monthly cost out loud. If I take an average bitrate of 3 Mbit/s, 1 million viewers is 3 Tbit/s of egress. Taking the average load over the whole day, that comes to hundreds of petabytes a month, so most of the cost is traffic, and the choice of bitrate and codec is directly money. Senior 161 Design a URL shortener that runs in several regions: how is the short code generated and how do you make the redirect fast? To generate codes without collisions I give each region its own ID range or Snowflake-style IDs and encode them in base62. The redirect path is read-only: a CDN/edge cache plus a KV store in the region, with writes going through asynchronous replication. Staff 162 Design a Dynamo-style distributed key-value store: how is data partitioned and replicated, and what happens when nodes fail? Keys are partitioned on a consistent hashing ring with virtual nodes, each key is replicated to N different nodes, and reads and writes use configurable quorums W and R. Failures are covered by hinted handoff, read repair and anti-entropy with Merkle trees, and conflicts are resolved with versions. Staff 163 A product is sold at the same time on your own site, a mobile app and two marketplaces, from three warehouses. How do you track stock without overselling and without losing sales for nothing? I don't keep stock as one number: per warehouse I track "physically on hand", "reserved" and "available to sell". The inventory service is the single source of truth, and the available quantity, minus a safety reserve, is pushed to channels through events; reservation on an order is atomic and time-limited. Staff 164 How do you model money movement in a payment system, and why do you need reconciliation? I don't update the balance as a single field: every movement is at least two immutable entries in a double-entry ledger, with debits and credits summing to zero. Reconciliation compares our ledger against the bank and provider reports and finds the differences. Staff 165 A bank calculates interest on millions of accounts and prepares statements every night. How do you build such a batch system reliably? I split the job into independent pieces and run them in parallel; each piece is idempotent and has a checkpoint, so after a crash it resumes where it stopped instead of starting over. The result is verified with control totals and published in two phases, and resources are capped so the daytime system isn't affected. Staff 166 If you need active-active writes in two regions, how do you resolve conflicting changes to the same record? First I separate out which data truly has to be written in two places: a lot can be tied to a "home region", which removes conflicts altogether. For the rest, last-write-wins, field-level merging or CRDTs, depending on the semantics of the data. Staff 167 Within one product, how do you choose different consistency levels for different features? For each feature I ask "what goes wrong if stale data is shown?". Strong consistency for money, inventory and unique constraints, read-your-writes for a user's own changes, and eventual is enough for counters and recommendations. Staff 168 How do you migrate a big monolithic database to a sharded schema without downtime? Step by step: first prepare the code so every query carries the shard key, then dual write to the new schema and backfill the old data, then compare with shadow reads, then move reads, and writes last. Every step must be reversible. Staff 169 A badly chosen shard key is causing problems in a running system. How do you replace it? I build a parallel set of shards on the new key, stream the data over with CDC, compare, and move traffic gradually. I don't "rehash in place": a new set and a way back are mandatory. Staff 170 How does a Snowflake-style ID generator work, and what are its clock-related risks? A 64-bit ID holds the time (milliseconds), a worker number and a sequence within that millisecond. It produces roughly time-sorted IDs without central coordination. The main risks are duplicate IDs if the clock goes backward, and worker number collisions. Staff 171 If each of five dependent services has 99.9% availability, what is the availability of the whole system, and how does that affect the design? With serial dependencies the probabilities multiply: 0.999^5 ≈ 99.5%, which is about 3.6 hours of downtime a month, not 43 minutes. So I cut the synchronous dependencies on the critical path and turn the rest into soft dependencies. Staff 172 What is a cell-based architecture and when is it worth moving to it? You split the system into identical, independent "cells": each has its own copies of the application, its own DB and cache, and users are partitioned across them. A failure or a bad deploy in one cell touches only its users, so the blast radius shrinks. Staff 173 In a system with hundreds of services, should each service make the "can this user do this action" authorization decision itself, or do you hand it to a central policy service? Authentication is centralized (one IdP, a token), but authorization is split: the coarse scope/role check lives in the gateway or a shared library, and the fine-grained decision that depends on the resource lives in the service that owns the data. A central policy engine helps you write policy in one place, but it must not turn into a network dependency on every request. Staff 174 In a system running in several regions, how do you decide which region to route a user request to: GeoDNS, anycast or a global load balancer? GeoDNS is simple, but failover is slow because of DNS caching, and it guesses location by the resolver. Anycast and a global L7 load balancer give fast failover and health-based routing. The decision also depends on where the data lives: you may need to send the request not to the nearest region but to the one that owns the data. Staff 175 The system depends on several external providers (payments, SMS, maps, KYC). How do you design it so their failures, limits and prices don't stop the business? Each provider sits behind our own interface (an adapter), the business code doesn't know the provider, and swapping becomes a configuration matter. Each adapter has a timeout, a circuit breaker, shared quota management and cost metrics; in critical places a backup provider or a queue, and when the state is unclear, a status query and reconciliation. Staff 176 After moving to microservices, how do you build queries and reports that combine data from several services, like "all of a customer's orders, payments and shipments"? There are three ways: combine by calling services at query time (API composition), a separate read model built from events (a projection), and a data warehouse. Composition for small interactive views, a projection for complex filters, the warehouse for reports; connecting directly to another team's DB is not an option. Staff 177 How true is the claim "Kafka gives you exactly-once", and how do you get it end to end? Kafka transactions give exactly-once only in a "read from Kafka, write to Kafka" chain. If an external DB or API is involved, the real guarantee is at-least-once delivery plus idempotent processing, so the effect of the result happens once. Staff 178 If the primary data is in Postgres and search is in Elasticsearch, how do you keep them in sync, and what do you do when the index gets corrupted? In the application I don't do "write to the DB, then write to ES". Changes go to a queue through CDC or an outbox, and an indexer writes them with versions. A way to rebuild the index from scratch is always ready: a new index, a full reindex, then swapping the alias. Staff 179 How do you design an order matching system for an exchange: latency, strict ordering and failures? For each instrument, matching runs on a single thread with an in-memory order book, in strict sequence, which is faster than distributed locks and deterministic. Orders are first written to a journal with a sequence number; after a failure the engine replays the journal to reach the same state, and a hot standby applies the same journal in parallel. Staff 180 A big monolith written by one team is now being split among 8 teams. How do you define service and team boundaries? I draw boundaries by business capability and data ownership, not by technical layer: things that change together stay together. Event storming and the history of what changes together in the code give candidate boundaries, and the team structure adapts to them, since Conway's law applies anyway. Staff 181 How do you build the upload and processing part of a platform where users upload large videos and watch them in many qualities? The file doesn't pass through the application servers: the client uploads straight to object storage in parts (multipart) with a presigned URL. Then an event goes to a transcoding queue, workers split the video into segments and encode them in parallel, and the result is distributed through a CDN. Staff 182 How do you build a CDN strategy for a site with many personalized pages? I split the page into shared and personal parts: shared HTML/JSON and static assets are cached on the CDN with a well-chosen cache key, while personal parts come through a separate, uncached API. I do invalidation by surrogate key (tag), not by URL. Staff 183 What do you do in a multi-tenant SaaS so that one big customer doesn't slow down the others? I put per-tenant limits at every layer: API rate limits, fair scheduling in queues, query limits in the DB, and if needed, moving the big tenant onto its own resources. Before that, I make every metric visible per tenant. Staff 184 How do you design an online judge (like LeetCode) that runs code submitted by users: isolation, queueing and scale? The code never runs on the API server: a submission goes into a queue, and workers run it in a sandbox (such as gVisor or Firecracker) with no network and limits on CPU, memory and time. The result comes back asynchronously, and for contest peaks the queue and the workers scale separately. Staff 185 How do you build a document system where several people edit at the same time, like Google Docs: OT or CRDT? Both bring simultaneous edits to the same result on every client. OT relies on a central server's ordering and is well studied for text; CRDT merges even without servers and suits offline work, but carries more metadata. The choice depends on the offline requirement and the architecture. Staff 186 How do you build "find the nearest drivers" in a taxi app for millions of drivers? A driver's location arrives every 3-5 seconds, so I write it not to a DB but to an in-memory geo index (geohash or H3 cells). The search takes the drivers in the passenger's cell and its neighbors and sorts them by real distance or travel time. Staff 187 How do you build a product analytics pipeline that gets billions of events a day? Events go through a light collector into Kafka, from there a stream loads them into a columnar database (ClickHouse, BigQuery and the like), and a raw copy is kept in cheap object storage. Real-time aggregates and exact nightly calculations can be separate layers, but I avoid two separate codebases. Staff 188 When do you choose event sourcing, and when is it too heavy for a project? When the history of events that led to the state matters to the business more than the state itself (a ledger, audit, a complex state machine), event sourcing pays off. In a plain CRUD domain it adds a permanent cost: schema evolution, projections and eventual consistency. Staff 189 When do you need an API gateway and a BFF (backend for frontend), and how do they turn into a problem? A gateway is for shared cross-cutting jobs: TLS, authentication, rate limiting, routing. A BFF gathers and shapes data for one kind of client (mobile, web). The trouble starts when they become a "new monolith" where business logic piles up. Staff 190 Should each service handle retry, timeout, mTLS and observability with a library, or do you hand them to a service mesh? How do you decide? With one language and a small number of services, a library (Spring + Resilience4j + OpenTelemetry) is cheaper and easier to understand. With many languages, hundreds of services and a mandatory uniform security policy, a mesh pays off, but it brings its own operational load. Staff 191 What would your recovery plan be if an entire region failed? How do you set RPO and RTO? RPO is how much data we're willing to lose, RTO is how fast we recover. I agree on them with the business per system, then match the replication type, the backups and the failover automation to those numbers, and I check the plan with regular real drills. Staff 192 If a user says "delete my data completely", how do you do it across dozens of services, caches, backups and analytical databases? Each service declares where personal data lives and subscribes to a central "erasure" event; the process collects a confirmation from every service. In immutable places (event log, backups) I encrypt the data with a per-user key and make it unreadable by deleting the key. Staff 193 How do you plan system capacity for a big once-a-year sales day (for example, 11.11)? I turn the business forecast into RPS for the critical paths, measure each component's real limit with load tests, and add capacity with headroom. A list of things that don't autoscale, a code freeze, and degradation flags tested in advance are part of the plan too. Staff 194 Your organization needs to pick a standard among Kafka, RabbitMQ and cloud queues (like SQS). What criteria do you use to decide? First I determine which messaging model is needed: a replayable event log (Kafka) or a work queue where each task is processed once (RabbitMQ, SQS). Then operational load, team experience and volume. Often I come out not with one standard but with two clear areas of use. Staff 195 How do you change the schema of events that many teams use without breaking each other? Events are a public API, so a schema registry and a compatibility rule (usually backward or full) are mandatory for them; CI rejects a change that breaks compatibility. If a breaking change is needed, a new versioned topic and a period of running both in parallel. Staff 196 One request calls 50 backends in parallel and the p99 latency is very bad. Why is that, and how do you reduce it? In a fan-out the response waits for the slowest backend: even if each one is slow only 1% of the time (at p99), the chance that at least one of the 50 is slow is ~40%. Hedged requests, answering with a partial result, and reducing the fan-out degree help. Staff 197 The same customer data has drifted apart across the CRM, billing and the main application database. How do you sort out data ownership and the "source of truth"? Each data element gets one owning system: only it writes, and the others receive a copy through events and don't change it. The existing differences are closed with a one-time cleanup, and after that kept in check with field-level ownership rules and continuous reconciliation. Staff 198 How do you introduce chaos engineering in an organization, and how do you choose the first experiments? First I define the system's steady state with a business metric, then form hypotheses from past incidents and architecture claims, and run experiments with a small blast radius and a stop button ready, in staging first and then in prod. The goal isn't to break things; it's to find wrong assumptions before an incident does. Staff 199 Cloud costs doubled in a year, and leadership is asking for a 30% cut. How do you approach it at the architecture level? First I make costs visible by service, team and feature, then I work on the 3-5 biggest items: idle capacity, storage and data transfer, wrongly chosen architecture. I weigh each saving together with its effect on reliability and speed. Staff 200 You've been asked to review another team's design document for a new system. What do you look at, and how do you deliver your feedback? First I check that the problem and requirements are clear, then that alternatives were really considered. Then failure modes, data ownership, scale assumptions and operations: who watches it, and how do they roll it back. I split my comments into "required" and "suggestion". Staff