You can write a working CRUD app and still freeze when somebody says “design Spotify”. That is not a gap in your coding. It is a gap in a different skill, and it is the skill that decides whether you are hired as a junior who takes tickets or as an engineer who is handed a blank page. Now that a model can write most of the code, the blank page is the job.
This article is a beginner’s course in software system design. It teaches one repeatable framework for turning a vague sentence into an architecture, the back-of-the-envelope arithmetic that tells you what the system will actually cost, and then it stops explaining and starts measuring: I built the classic hotel-booking race condition on PostgreSQL 18.6 and let 50 guests fight over 10 rooms, to show you exactly what “design for concurrency” means when nobody designs for it.
Who this is for
Anyone who has just started learning system design: BCA, BSc CSIT, BIT and Class 12 students, self-taught developers, and working juniors heading into a first design interview. You need to know what a table, an HTTP request and a SELECT are. You do not need to have touched a load balancer, Kafka, Redis or a cloud console. Every concept is built from the problem up, and every number in the lab is one I ran. If you want the short version for an exam, jump to the exam-ready answers, then come back and read why they are true.
The framework and the three worked systems come from Hayk Simonyan’s free 3-hour 16-minute course Design Software Systems Like a Senior Engineer, published on freeCodeCamp on 13 October 2026. This article is not a transcript of it. I have reorganised the material for someone learning the subject for the first time rather than revising for an interview next week, worked the arithmetic out in the open instead of rounding it off-screen, and added a measured lab for the one part of the course that cannot be learned by watching: concurrency. Watch the course for the full WhatsApp and Booking.com walkthroughs. Read this first so the course makes sense.
How this was tested. I did not want the concurrency section to rest on “race conditions are bad”. So it is a real experiment on one laptop: PostgreSQL 18.6 on Debian, 50 Python threads released from a barrier so they hit the database in the same instant, five trials of every variant, with the row counts read back from the table afterwards. Every count, millisecond and error code in Part 8 comes from those runs. Reproduce the lab at the end gives you the two scripts and the exact command.
Part 1. What system design actually is
Writing a function is a closed problem. Somebody hands you the input type and the expected output, and the solution is either right or wrong; you can run it and find out. System design is the opposite kind of problem on every axis. The requirements arrive vague and it is your job to make them specific. There is no single correct answer. And nothing can be executed to check you, because the thing you are designing does not exist yet.
In plain words: coding answers “how do I make this work?”. System design answers “what should exist, how many of it, and what happens when a piece of it dies?”. The second question has no compiler.
That is why the subject feels slippery when you start. You are used to problems with a check mark at the end. Here the check mark is replaced by a judgement: given what this system is for, were your trade-offs reasonable, and can you say out loud why you made them? A design is never finished, only defensible.
It shows up in four different shapes once you are being interviewed, and it is worth knowing all four, because only the first is what people mean by “system design interview”: designing a system or feature from scratch on a whiteboard; being shown a bottleneck in the company’s existing infrastructure and asked what you would do; being walked back through a project on your own CV to see whether you understood the architecture you shipped; and plain conceptual questions that probe how deep your knowledge goes. The first is the one you can practise. The third is the one juniors lose most often, and it costs nothing to prepare: be able to draw your own final-year project as a diagram, and know why you chose each piece of it.
Part 2. What you are actually scored on
Here is the misconception that does the most damage to beginners. People prepare for system design by memorising architectures: the Spotify diagram, the WhatsApp diagram, the URL-shortener diagram. Knowing a few is genuinely useful. But the diagram is not what is being marked. It is the residue of five things that are being marked, and you can produce a textbook-correct diagram while failing four of them.
Read that bottom line again, because it reframes the whole exercise. An interviewer is not really curious about your Spotify architecture; they will never build it. They are using a 60-minute design conversation as the cheapest available simulation of working with you. Every dimension maps onto a Tuesday-afternoon behaviour. If you cannot manage an hour, you will not manage a sprint. If you choose Kafka because you know the word, you will choose Kafka in production for the same reason. If you build before you ask, you will deliver the wrong feature and burn two weeks.
This is also why the advice “treat the interviewer as a colleague” is not a soft skill. Two failure modes are common and both are communication failures: going silent and drawing for ten minutes, or talking continuously to fill every pause without ever inviting an opinion. The fix for both is the same, and it is mechanical: at the end of each step, stop and ask one question. Does this scope look right before I move to the data model? If they say yes, you have confirmation. If they hesitate, you have just been handed a hint you would otherwise have missed, and you can still spend your remaining time on the right thing.
Part 3. The five-step framework
Knowing concepts is not enough, because the hard part of a design conversation is not recall, it is navigation. You have roughly an hour, five areas to cover, and no natural signal telling you when to stop talking about one and start on the next. Without a structure you will do what almost everyone does untrained: spend 35 minutes lovingly detailing the high-level architecture, and then discover you have four minutes left for the data model, scaling and failure combined.
So the framework below is less a recipe for good design than a budget. Five steps, each with a time allowance you say out loud at the start.
In plain words: clarify what you are building, decide what the data and the endpoints look like, draw the components and trace a request through them, work out what breaks under load, then say what you traded away and what you would do next. Ask “anything missing?” between each pair.
Two notes before we walk through the steps. Steps 2 and 3 are deliberately interchangeable. Some people need to see the entities before the boxes make sense; others need the boxes before the entities do. Pick the order that matches how you think, say which you are doing, and be consistent. And if the interview is 45 minutes rather than 60, the time comes out of steps 2 and 3, never out of step 1 — cutting requirements to save time is how you end up designing the wrong system quickly.
The last step is the one beginners skip because it feels like admitting defeat. It is the opposite. Nobody can design a production system in an hour, and the interviewer knows it, so a design presented as finished reads as naivety. Summarising what you prioritised, what you sacrificed and what you would build next if the load grew tenfold is the single clearest signal that you understand your own design’s limits. Say the sacrifices out loud with their reasons.
Part 4. Step 1: clarify requirements
“Design Spotify” is not a task. Spotify took many teams many years, and no honest answer to it exists in an hour. What is being asked is narrower and much more reasonable: choose a defensible slice of Spotify, say clearly which slice, and design that. The first five to ten minutes are where you do the choosing, in the open, with the interviewer.
Requirements come in two kinds and beginners reliably collect only the first.
| Functional requirements | Non-functional requirements | |
|---|---|---|
| The question they answer | What can a user do? | Under what constraints must it do it? |
| Form | verbs: upload, search, play, book, cancel | numbers: users, ratio, milliseconds, nines |
| Examples | an artist uploads a song; a user searches and plays it; a user makes a playlist | 500,000 users; 30 million songs; reads vastly outnumber writes; search under 500 ms; 99.9% available |
| What they decide | the entities, the endpoints, the screens | the storage, the number of machines, the database choice, whether you need a cache or a queue at all |
| If you skip them | you design the wrong product | you design an architecture with no idea whether it is 10× too small or 100× too big |
| Also state | what is explicitly out of scope | which parts need strong consistency and which can be eventual |
For picking the functional slice there is a test worth memorising, and it comes from the Booking.com walkthrough in the course: which features, if you removed them, would mean the thing is no longer Booking.com? Search by location and dates survives that test. Loyalty points do not. Run the test out loud and you will produce a defensible scope in about ninety seconds, and you will have shown the interviewer how you prioritise, which is one of the five dimensions.
The non-functional list is shorter but it carries more design weight. For most systems you want five numbers and one sentence:
- Scale. Daily or monthly active users, and the size of the main collection (songs, rooms, messages).
- Read-to-write ratio. Almost every consumer system is read-heavy, often by 100:1 or more. This single ratio decides whether you reach for read replicas and caching, or for write sharding.
- Latency. A target per operation, not for the system. Search under 500 ms and booking confirmation in two to three seconds are different promises, and the second one buys you room to do real work.
- Availability. Expressed as acceptable downtime. “99.9%” is eight hours and 46 minutes a year, which is a very different system from 99.99%.
- Consistency, per operation. Not for the whole system. This is the sentence, and it is the most senior thing you can say in the first ten minutes.
That last one deserves its own moment, because it is where the hotel-booking system in Part 8 is won or lost. The correct answer for a booking system is not “strong consistency” and it is not “eventual consistency”. It is: two guests must never hold the same room for the same night, so the reservation write is strongly consistent and non-negotiable; but the search results a guest browses can be a few seconds stale, because a room appearing in search that was taken moments ago is an annoyance, not a double charge. Same system, two different answers, chosen per operation. Say that and you have demonstrated technical judgment before drawing a single box.
The habit that makes step 1 work
End it with one sentence: “So: artists upload, users search and play, users manage playlists; recommendations, social features and payments are out of scope; 500,000 users, 30 million songs, read-heavy, search under 500 ms. Does that scope look right before I move on?” If the answer is a hesitation, you have just saved the interview.
Part 5. Step 2: the arithmetic that decides the architecture
This is the step that separates a design from a drawing, and it is also the step beginners find least intimidating once they try it, because it is arithmetic you learned at fourteen. It is called back-of-the-envelope estimation, and the whole point is that the answer only has to be right to within a factor of two or three. You are not budgeting; you are finding out which part of the system is the problem.
Let us do it properly for the music platform, with every number shown. Requirements from step 1: 500,000 users, 30 million songs, average listen 3.5 minutes, audio delivered at 128 kbit/s for standard quality.
First, how big is one song? Courses usually hand you “about 3 MB” and move on. Derive it instead, because the derivation is the part you can reuse on a system nobody has pre-chewed for you. A 3.5-minute song is 210 seconds. At 128 kbit/s that is 128,000 × 210 ÷ 8 bytes, which is 3.36 MB. So 3 MB is a fair working average, and now you also know what the premium tier costs you: at 320 kbit/s the same song is 8.4 MB, two and a half times the storage and two and a half times the bandwidth bill, for one checkbox in the product spec.
| Quantity | Arithmetic | Result |
|---|---|---|
| One song, standard quality | 128,000 bit/s × 210 s ÷ 8 | 3.36 MB |
| One song, premium | 320,000 bit/s × 210 s ÷ 8 | 8.4 MB |
| Raw audio library | 30,000,000 × 3 MB | 90 TB |
| Audio with replicas and re-uploads | 90 TB × 3 | 270 TB |
| Song metadata | 30,000,000 × 100 B | 3 GB |
| User metadata | 500,000 × 1 kB | 0.5 GB |
| Daily egress | 500,000 users × 12.5 songs × 3.5 MB | 21.9 TB/day |
| … as a sustained bitrate | 21.9 TB × 8 ÷ 86,400 s | 2.03 Gbit/s average |
| … at a 5× evening peak | 2.03 Gbit/s × 5 | 10.1 Gbit/s |
Now look at what the arithmetic just told you, because it is not what a beginner expects. All the metadata in the entire system — every song title, artist reference, duration, URL, every user profile and playlist — adds up to 3.5 GB. That is 0.0039% of the storage. It fits in RAM on a laptop. The audio files are 99.996% of the problem.
That single insight redirects the entire design. You now know that the audio does not belong in a database at all; it belongs in object storage such as S3, served through a CDN, and the interesting questions are about signed URLs, cache eviction and which continent the bytes leave from. You also know not to spend twenty minutes sharding the metadata database, because 3.5 GB does not need sharding and saying so proves you did the arithmetic.
Push the numbers to a growth scenario and the lesson sharpens rather than reverses. At 50 million users and 200 million songs, audio becomes 600 TB raw and nearer 1.8 PB with replicas, daily egress passes 2 PB, and plays run at about 7,200 per second average and 36,000 per second at a 5× peak. Meanwhile all the metadata reaches 71 GB. A hundredfold growth in users, and the metadata store still fits comfortably on a single well-specified machine with replicas for reads. The thing that needed rearchitecting was never the database.
Rule of thumb
Estimate before you architect, and estimate the thing you are tempted to ignore. The component you understand least is usually where the capacity actually goes. If your estimate does not change any decision, you estimated the wrong quantity.
You need very few figures in your head to do this. One day is 86,400 seconds, near enough 100,000 for a sanity check. A million seconds is about twelve days. One byte is eight bits, which is the conversion beginners drop most often and it is a factor of eight in the answer. And when you need a peak, multiply the average by five and say that you are doing so — stating the multiplier is what makes it an estimate rather than a guess.
Part 6. Step 3: the high-level architecture
If your mind goes blank in front of an empty whiteboard, start with the four components that are present in very nearly every system, and justify each one as you draw it: API servers that accept requests, a load balancer that spreads traffic across them, a database that persists state, and optionally a cache for data that is read far more often than it changes. That is a complete and honest architecture for thousands of users. Everything else — queues, search clusters, CDNs, shards — gets added only when a requirement or an estimate forces it, and in an interview you say which one forced it.
Then do the thing that actually earns marks: trace one request all the way through, out loud, and back again. Not the boxes, the journey.
That separation is the most valuable idea in this part of the article, and it generalises far beyond music. Your API servers handle the small traffic: authentication, a database row, a JSON response. The large traffic — audio, video, images, file downloads — is handed off by giving the client a time-limited URL and letting it fetch the bytes straight from storage or a CDN edge near it. Route 90 TB through your API servers and you need a fleet of them to do nothing but copy bytes, and you pay for the same bytes twice.
Here is the read path, which is what you should narrate when asked how playing a song works:
- The user presses play. The app sends
GET /songs/{id}. - The load balancer picks a healthy API server — round-robin or least-connections, and it is also the thing doing health checks.
- The API server validates the JWT. If that fails, nothing below happens.
- It reads the song row from SQL (or from cache, if it is there).
- It generates a signed, expiring URL for the audio file.
- It returns metadata plus that URL. The response is a few hundred bytes.
- The app range-requests the audio through the CDN, which streams it in chunks so playback starts before the file has arrived.
- Separately, the app posts
/songs/{id}/playso the play is counted. This is analytics, it is allowed to be eventually consistent, and it must never block playback.
And the write path, when an artist uploads, is the read path’s mirror with validation in front: the file size and format are checked first and rejected cheaply if wrong; the audio goes to object storage; the duration and bitrate are extracted; a metadata row is inserted into SQL; the CDN is told to invalidate anything stale so listeners see the new release immediately; and only then does the artist get a success response.
Two details in that figure are worth saying explicitly in an interview, because they are the kind of thing that reads as practical depth. The API servers are marked stateless, and that word is doing real work: because no session or file lives on them, scaling out is just launching more of them behind the load balancer. The moment you keep a user’s session in a server’s memory, you have made horizontal scaling a migration project. And the cache is annotated with a TTL and an invalidation rule, because “add a cache” is not a design — a cache without a stated expiry and a stated way of being wrong is just a bug with better latency.
Part 7. Step 4: the data model and the API contract
For the data model you need four things and no more: the main entities, how they relate, the keys and indexes, and roughly how big one record is. For the music platform the entities fall out of the requirements almost mechanically — users, artists, songs, playlists — and the only structural decision is what to do about the two many-to-many relationships, because a playlist holds many songs and a song sits in many playlists, and a song may have several artists.
| Table | Key columns | Why it exists |
|---|---|---|
users | id PK, email, password_hash, subscription_type, country | who is listening, and what quality they are entitled to |
artists | id PK, name, country | kept separate from users: an artist is a different thing with different fields |
songs | id PK, title, duration, file_url | file_url is the bridge to object storage; the row is ~100 B |
playlists | id PK, owner_id FK → users | a playlist must belong to someone |
playlist_items | playlist_id + song_id, position, added_at | junction table for playlist ↔ song, and position is why it needs to exist rather than an array |
artist_songs | artist_id + song_id | junction table for collaborations |
Now justify the database choice, because an unjustified choice scores as a guess even when it is the right answer. SQL here, and the reason is visible in the table above: the useful queries are joins. Every song by an artist this user follows crosses four tables. Relational databases are built for exactly that, they give you foreign keys that stop a playlist pointing at a song that no longer exists, and — the part that matters most in Part 8 — they give you transactions. Then add the comparison unprompted: a document store would make each playlist a self-contained document and the many-to-many queries awkward and duplicated, which is a reasonable trade for a system with no joins and this is not one.
Indexes follow from the read patterns rather than from habit: songs.title and artists.name because users search on them, and playlist_items.song_id because “which playlists contain this song” is a query the product needs. An index on a column nobody filters by is pure write cost.
The API contract is the other half of this step, and the thing being tested is consistency rather than cleverness. Plural nouns, the resource in the path, the parameters in the query string, and the same conventions everywhere.
| Endpoint | Purpose |
|---|---|
GET /search?q=&type=song&limit=20&offset=0 | search, typed, paginated |
GET /songs/{id} | metadata plus the signed streaming URL |
GET /artists/{id}/songs?limit=20 | an artist’s catalogue |
POST /playlists | create: name, public or private |
PUT /playlists/{id}/songs | add songs, with position |
DELETE /playlists/{id}/songs/{songId} | remove one song |
POST /songs/{id}/like | favourite a song |
GET /users/me/playlists | the caller’s own playlists |
POST /users/me/following | follow an artist |
limit and offset on every collection: an endpoint that can return an unbounded list is an outage waiting for a popular artist.Mention pagination, error shapes, rate limiting and versioning here even briefly. They take fifteen seconds each and they are what distinguishes someone who has operated an API from someone who has only consumed one.
Part 8. Step 5: where it breaks. A measured lab
Everything so far you could have learned by reading. This part you cannot, and it is the part that the five-dimension list calls practical depth: knowing what actually happens to a design when real users arrive at the same moment. So we are going to stop designing and run an experiment.
Switch systems, to the hotel reservation problem. A beginner reads “design Booking.com” and sees CRUD: hotels, rooms, bookings, a bit of caching, done. That reading is wrong, and the reason is a single scenario. Two guests want the last Deluxe double for Christmas night. Both of their phones check availability, both see one room free, both press Book. A system built the obvious way will confirm both, charge two cards, and hand you an angry phone call in the morning. That is a race condition, and inventory systems are interview favourites precisely because they force you to deal with one.
The obvious way looks completely reasonable when you write it:
-- how many rooms of this type are already taken for that night?
SELECT count(*) FROM reservation
WHERE room_type_id = 1 AND stay_date = '2026-12-25';
-- the application compares that to total_rooms, and if there is space:
INSERT INTO reservation (room_type_id, guest, stay_date)
VALUES (1, 'guest-07', '2026-12-25');Read it again and you will not find a bug, because there isn’t one in the logic. The bug is in the gap. Between the SELECT finishing and the INSERT landing, time passes: your application compares numbers, perhaps calls a payment provider, and the request travels the network twice. Any other guest who reads during that gap sees the same stale count that you did.
Many beginners have been told that transactions prevent this. They do not, at least not by default, and this is the single most useful thing in this article to actually verify rather than believe. PostgreSQL’s default isolation level is read committed — I checked, the lab reports it — and read committed promises only that you will not see another transaction’s uncommitted data. It says nothing about the gap. Wrapping the two statements in BEGIN and COMMIT changes nothing about this bug.
The experiment
Ten rooms. Fifty guests. All fifty released from a thread barrier so that they hit PostgreSQL 18.6 in the same instant, each inside a transaction, each running exactly the check-then-insert above. Five trials per variant, and after each trial I read the row count back out of the table. Here is what the database contained.
| Design | Rooms sold (capacity 10) | Oversold by | Median wall time | What the guests were told |
|---|---|---|---|---|
| Check-then-insert, no delay in the gap | 35–38 (median 38) | 25–28 | 115 ms | 38 confirmations |
| Check-then-insert, 20 ms of work in the gap | 50, every trial | 40 | 137 ms | all 50 confirmed |
SELECT … FOR UPDATE on the room type | 10, every trial | 0 | 1,169 ms | 10 confirmed, 40 told full |
SERIALIZABLE, no retry loop | 1, every trial | 0 | 125 ms | 1 confirmed, 49 errors |
SERIALIZABLE with retries | 10, every trial | 0 | 379 ms | 10 confirmed · 394–436 wasted attempts |
| Atomic claim, slow work outside the lock | 10, every trial | 0 | 128 ms | 10 confirmed, 40 told full |
Take the second row seriously for a moment. With a mere 20 milliseconds of work in the gap — far less than a real payment API call — the naive design sold 50 rooms out of 10, in all five trials, and told all fifty guests they were confirmed. Not a rare race that bites you one night a year. A total failure, reproducibly, the first time concurrency arrives.
Fix 1: lock the row. Correct, and eight times slower
The direct fix is to stop other transactions reading the thing you are about to change. SELECT … FOR UPDATE takes a lock on the room-type row, and every other guest queues behind it.
BEGIN;
SELECT total_rooms FROM room_type WHERE id = 1 FOR UPDATE; -- others now wait here
SELECT count(*) FROM reservation WHERE room_type_id = 1 AND stay_date = '2026-12-25';
-- ... decide, then insert ...
COMMIT; -- lock releasedIt works: 10 rooms, zero oversold, every trial. And it cost 1,169 ms against 137 ms for the broken version — 8.5 times slower. The reason is visible in the code: the lock is held for the entire transaction, which includes the 20 ms of work in the gap. Fifty guests serialised behind a 20 ms critical section take at least a second, by arithmetic. Make it a real payment call at 300 ms and fifty guests take fifteen seconds, and guest fifty has long since given up.
In plain words: locking works, and the cost of a lock is everything you do while holding it.
Fix 2: ask for SERIALIZABLE. Correct only if you write the retry loop
The textbook answer is to raise the isolation level. SERIALIZABLE guarantees the outcome is as if the transactions had run one after another, which is exactly the guarantee we want. So I ran it, and the result is the most instructive row in the table: one reservation, and 49 transactions killed with SQLSTATE 40001, serialization_failure.
That is not PostgreSQL failing. It is PostgreSQL doing precisely what it promised and refusing to commit anything it cannot prove was serialisable. The point everybody skips is that SERIALIZABLE does not make concurrency work, it makes conflicts visible, and it hands you the job of retrying. Add the retry loop and you get the correct answer:
for attempt in range(25):
try:
with conn: # one transaction per attempt
cur.execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")
# ... check availability, then insert ...
break # committed
except psycopg2.Error as e:
if e.pgcode == "40001": # serialization_failure
continue # a conflict: try again
raiseWith retries: 10 rooms, zero oversold, 379 ms — and between 394 and 436 wasted attempts across the 50 guests, in every trial. Each of those is work the database did and threw away. Serializable is a genuinely good tool, especially for logic too complicated to express as one statement, but it is a bargain: the database guarantees correctness, you supply the retries and absorb the wasted work. An interviewer who hears “I’d use serializable” will ask what happens on conflict, and “it retries” is the answer that separates having read about it from having used it.
Fix 3: make the claim atomic, and do slow work outside it
Now the design a senior engineer reaches for, and the reason this lab exists. Stop asking “is a room free?” and then separately taking it. Those two steps are the bug. Instead, claim a room in a single statement that only succeeds if one was available, by keeping a counter and letting the database evaluate the condition and the change together:
-- one statement: the check and the claim cannot be separated
UPDATE room_type
SET booked = booked + 1
WHERE id = 1 AND booked < total_rooms
RETURNING booked;
-- no row came back -> the hotel is full, tell the guest honestly
-- a row came back -> the room is yours; now take the payment, send the emailThere is no gap to lose a race in, because there is no gap. UPDATE locks the row, re-evaluates booked < total_rooms against the committed value, and either changes it or matches nothing. Fifty guests run it; exactly ten get a row back.
But the measurement shows that one more decision matters just as much, and it is the detail I would most like a beginner to take away. I ran this fix twice. Once with the slow 20 ms of work inside the same transaction as the claim, and once with the claim committed immediately and the slow work done afterwards:
| Atomic claim, where the slow work happens | Rooms sold | Median wall time |
|---|---|---|
| inside the transaction holding the claim | 10 | 357 ms |
| committed first, slow work afterwards | 10 | 128 ms |
| … for comparison, the broken design | 50 | 137 ms |
128 milliseconds, correct, against 137 milliseconds, broken. The correct design was faster than the incorrect one. There was no trade-off to make here at all — no cleverness, no new technology, nothing to buy. The only difference between the system that oversells 40 rooms and the system that does not is that somebody thought about the order of operations before writing the code. That is what this whole subject is for, and it is why the planning comes before the keyboard.
The rule worth memorising
Claim the scarce thing in one atomic statement, commit, then do the slow work. Never hold a lock across a network call. If the slow work then fails, release the claim in a compensating step — which is exactly why real booking systems hold rooms for fifteen minutes and free them on a timer.
The other race: the guest who presses Book twice
There is a second concurrency bug in every booking system and it has nothing to do with other guests. It is one impatient guest on a bad connection, tapping Book because nothing seemed to happen, or a mobile client retrying a request it never got an answer to. The fix is an idempotency key: the client generates a unique id for the intent and sends it with every attempt, and the database is told that key must be unique.
ALTER TABLE reservation ADD COLUMN idem_key text UNIQUE;
INSERT INTO reservation (room_type_id, guest, stay_date, idem_key)
VALUES (1, 'guest-impatient', '2026-12-25', 'req-7f3a2c')
ON CONFLICT (idem_key) DO NOTHING
RETURNING id; -- a row: you created it. no row: it already existed, return that oneTwenty simultaneous submissions of the same request, five trials:
| Design | Taps | Reservations created | Deduplicated |
|---|---|---|---|
| No idempotency key | 20 | 20 | 0 |
| Unique idempotency key | 20 | 1 | 19 |
Note what makes this work: the guarantee lives in the database as a constraint, not in the application as a check. An application-level “have we seen this key?” lookup is just the check-then-insert bug again, wearing a different hat. The constraint cannot be raced because the database enforces uniqueness at commit.
This is also the right answer to a question you will be asked eventually: what happens if the payment succeeds but your server crashes before writing the reservation? The client retries with the same idempotency key, and the retry is safe. Idempotency is what makes retries possible, and retries are what make distributed systems survivable.
Which fix, when
| Situation | Reach for | Because |
|---|---|---|
| Claiming one unit of a counted inventory | atomic conditional UPDATE | no gap, no lock held across slow work, measured fastest |
| Logic too complex for one statement | SERIALIZABLE + retry loop | the database proves correctness; you pay in retries |
| You must read several rows, then decide | SELECT … FOR UPDATE | simple and obvious; keep the transaction tiny |
| The same request may arrive twice | unique idempotency key | a constraint cannot be raced; a lookup can |
| Reads that may be a little stale | replicas and cache | search can be eventually consistent; the booking cannot |
Part 9. Scaling, in the order you should actually do it
Scaling is step four, and the most common beginner error is doing it first. Starting a design with “we’ll shard the database and put Kafka in front” for a system with 5,000 users reads as someone repeating vocabulary. Start simple, then let a specific pressure justify each addition. For the music platform growing to 50 million users, the order looks like this, and notice how much of it the arithmetic from Part 5 already decided.
- Add CDN edges per region. This is first because egress dominates, and an LRU eviction policy at the edge means popular songs are served near the listener and cold ones fall back to origin.
- Scale the API servers out. Free, because you designed them stateless. Add instances behind the load balancer across availability zones.
- Split reads from writes. One primary takes writes; read replicas serve the metadata reads, which are the overwhelming majority. This is the single highest-leverage database change for a read-heavy system.
- Replicate object storage per region, so an artist in Europe uploads to Europe and a listener in Asia streams from Asia.
- Shard, only if you must. And for this system, measure first: metadata at 50 million users is 71 GB. It does not need sharding. Saying that out loud, with the number, is worth more than drawing shards you cannot justify.
The same step is where you name single points of failure and say what you would do about each one, mention multi-AZ replicas and auto-scaling, and — the part almost everyone forgets — say how you would know something was wrong. What you monitor, what you alert on, and at what threshold. API latency percentiles and error rates, not averages. That one paragraph about observability is, by the course’s own account and in my experience reading juniors’ design documents, one of the clearest senior signals available to you, and it costs thirty seconds.
Part 10. The pyramid: why this is the skill that pays
Here is the argument for taking any of this seriously, drawn as a pyramid because the proportions are the argument.
The honest version of the career argument is this. Coding is the layer that has become cheap. A model will write your INSERT faster and more correctly than you will, and it will do it at three in the morning. What a model will not reliably do is notice that your check-then-insert oversells 40 rooms the first time fifty people arrive at once, because that failure is invisible in the code and only appears in the design. The skill that is scarce is deciding what should exist, how much of it, and what happens when a piece dies.
In plain words: the base of the pyramid is the part you cannot outsource, and it is the part you can start practising today with no cloud account and no money.
How to actually get better, concretely
Memorising architectures does not work, because the interview question will be a system you have not memorised and the job certainly will be. What transfers is the framework plus the habit of reasoning about trade-offs out loud. Six things that actually build it, roughly in order of how much they pay:
- Draw a system you already built. Your final-year project, your internship work. Boxes, arrows, one request traced end to end. You will discover you cannot explain a piece of it, and that discovery is the lesson. This also happens to be an interview format in its own right.
- Do the arithmetic on apps you use. How much storage does a Nepali e-commerce site need for product images at 50,000 products? How much egress does a 10,000-student college portal use on results day? Ten minutes with a calculator, and estimation stops being intimidating.
- Run the lab in this article. Not read it — run it. Then change a number: 200 guests, 5 rooms, 200 ms in the gap. Watching your own terminal print 50 reservations for 10 rooms teaches you something that no amount of “use transactions” ever will.
- Practise saying trade-offs out loud. Literally out loud, to a wall if necessary. “I chose SQL because the queries are joins; a document store would make playlists self-contained but the many-to-many queries awkward.” The skill being tested is articulation, and articulation only improves by articulating.
- Design one system a week on paper, timed to 45 minutes with the five-step budget. A URL shortener, a parking system, a bus-ticket booking system for Nepal, a notice board for a college. Timing it is the point; the budget is the skill.
- Then watch the long courses. Including the one this article is based on. They will make far more sense once you have felt the problems they are solving, and you will be able to tell which parts are fundamental and which are one person’s preference.
And do not worry that a real design takes longer than an hour. It does. Nobody expects a perfect system; they expect to watch you think, hear you weigh options, and see you notice what might break.
Common beginner mistakes, with the fix
| Mistake | Why it costs you | Do this instead |
|---|---|---|
| Designing before clarifying | The clearest red flag there is. You may design a correct system for the wrong problem. | Spend the first 5–10 minutes on requirements. Always. |
| Picking a database without saying why | An unexplained choice is scored as a guess, even when it is right. | Name the alternative and the trade-off, unprompted. |
| Skipping the arithmetic | You cannot tell whether your design is 10× too small or 100× too big. | Estimate storage, bandwidth and QPS. Show the working. |
| Starting with Kafka, shards and Redis | Reads as vocabulary, not judgment. It is also the wrong engineering. | Start with four components. Add each one only when a requirement forces it. |
| Drawing in silence, or narrating non-stop | Both fail the communication dimension. | Check in at every step boundary with one question. |
| “Transactions will handle concurrency” | Measurably false at the default isolation level. See Part 8. | Say which isolation level, or which lock, or which atomic statement. |
| Presenting the design as finished | Nobody designs production in an hour; claiming you did reads as inexperience. | End with sacrifices, their reasons, and what you would do at 10×. |
| Forgetting how you would notice a failure | Monitoring is the most-skipped senior signal. | Name the metrics, the thresholds and the alerts. |
Exam-ready answers
Short, written-answer versions for BCA, BSc CSIT and BIT papers, where this material appears under database transactions, concurrency control and distributed systems rather than under “system design”.
1. What is a race condition? Give an example and two ways to prevent it.
A race condition occurs when the result of an operation depends on the relative timing of concurrent operations, so the same inputs can produce different outcomes. Example: two users book the last hotel room. Each transaction reads the availability count, both see one room free because neither has committed yet, and both insert a reservation — selling one room twice. Prevention: (i) pessimistic locking, using SELECT … FOR UPDATE so the second transaction waits; (ii) an atomic conditional update, UPDATE room_type SET booked = booked + 1 WHERE id = ? AND booked < total_rooms, which performs the check and the change in one indivisible statement. A third option is the SERIALIZABLE isolation level with an application retry loop.
2. Distinguish functional and non-functional requirements.
Functional requirements state what the system does: the use cases, expressed as verbs (a user searches, plays, books, cancels). Non-functional requirements state the constraints under which it must do them, expressed as measurable quantities: number of users, read-to-write ratio, latency targets, availability, consistency and security. Functional requirements determine the entities and endpoints; non-functional requirements determine the architecture, the capacity and the technology choices. A system can satisfy every functional requirement and still be useless if it takes thirty seconds to answer.
3. Explain concurrency control. Compare pessimistic and optimistic approaches.
Concurrency control is the set of techniques a DBMS uses to let many transactions run at once while preserving isolation, so the result is equivalent to some serial order. Pessimistic control assumes conflict is likely and prevents it by locking data before use (SELECT … FOR UPDATE, two-phase locking); other transactions wait, so throughput falls under contention but no work is wasted. Optimistic control assumes conflict is rare, lets transactions proceed, and checks at commit whether the result was serialisable, aborting if not (PostgreSQL’s SERIALIZABLE, which uses serializable snapshot isolation). Optimistic control is faster when conflicts are rare and wasteful when they are common: in the measured lab in this article, 50 transactions contending for 10 rooms produced roughly 420 wasted retries.
4. List the SQL isolation levels and state what each prevents.
| Level | Prevents | Still allows |
|---|---|---|
| Read uncommitted | nothing | dirty reads, non-repeatable reads, phantoms |
| Read committed | dirty reads | non-repeatable reads, phantoms |
| Repeatable read | dirty and non-repeatable reads | phantoms (in the standard) |
| Serializable | all three | nothing — but transactions may be aborted and must be retried |
PostgreSQL’s default is read committed, which I confirmed in the lab, and PostgreSQL does not implement read uncommitted separately (it behaves as read committed). MySQL and MariaDB’s InnoDB engine default to repeatable read instead — worth knowing if you work in XAMPP, though note I measured only PostgreSQL here, so treat the MariaDB behaviour as documented rather than as something this article tested. In either case, the default level does not prevent the check-then-insert bug, because the problem is not a dirty read: each read was correct when it ran.
5. Differentiate vertical and horizontal scaling. Why must servers be stateless?
Vertical scaling (scaling up) means giving one machine more CPU, RAM or disk. It is simple and requires no application change, but has a hard ceiling and a single point of failure. Horizontal scaling (scaling out) means adding more machines behind a load balancer. It has no practical ceiling and gives redundancy, but only works if any machine can serve any request. That is why application servers must be stateless: if a user’s session or uploaded file lives in one server’s memory or disk, requests must be routed back to that server, and adding capacity becomes a migration. State belongs in a shared store — a database, a cache such as Redis, or object storage.
6. What is idempotency and why does it matter?
An operation is idempotent if performing it several times has the same effect as performing it once. In HTTP, GET, PUT and DELETE are idempotent by definition; POST is not. This matters because networks fail in a way that is impossible to distinguish from the server failing: when a client gets no response, it cannot tell whether the request was processed. The safe design is to make the operation idempotent so the client can retry freely, usually with an idempotency key — a unique id the client attaches to the intent, stored under a unique constraint, so a duplicate request returns the original result instead of creating a second record. In the measured lab, 20 simultaneous submissions created 20 reservations without a key and exactly 1 with one.
7. What is back-of-the-envelope estimation? Give a worked example.
It is approximate arithmetic done before designing, to establish the order of magnitude of storage, bandwidth and request rate, so that architectural decisions are driven by quantity rather than habit. Accuracy within a factor of two or three is sufficient. Worked example, for a music service with 30 million songs averaging 3 MB: audio storage is 30,000,000 × 3 MB = 90 TB, while song metadata at 100 bytes per row is 30,000,000 × 100 B = 3 GB. The conclusion drives the design: audio must go to object storage behind a CDN, and the metadata database is small enough to need no sharding at all.
Frequently asked questions
Do I need to know system design as a fresher or junior?
You will rarely be asked to design a full system in a fresher interview, but you should expect to be asked about the architecture of your own projects, and that is the same skill with a smaller scope. The depth expected rises with the level: conceptual awareness for a junior, full whiteboard design for senior and staff roles. Mid-level interviews increasingly include it, for the reason in Part 10 — the coding layer is no longer where candidates are differentiated.
Is it enough to memorise a few architectures?
No, though it helps as a starting vocabulary. The question you get will be a system you have not memorised, and four of the five scored dimensions are about how you behave rather than what you recall. Learn the framework and practise reasoning out loud instead.
Does wrapping my code in a transaction prevent double booking?
No, and this is worth being precise about because it is the most common misconception in the subject. At PostgreSQL’s default read committed level, a transaction guarantees you will not read uncommitted data and that your writes commit together. It does not stop two transactions from reading the same availability count and both acting on it. In the lab, the naive design ran entirely inside transactions and still sold 50 rooms out of 10. You need a lock, a serialisable isolation level with retries, or an atomic conditional update.
Which fix should I use for inventory?
For claiming one unit of a counted inventory, the atomic conditional UPDATE with a counter, committed before any slow work. It was both correct and the fastest option measured, at 128 ms against 1,169 ms for row locking. Use SELECT … FOR UPDATE when you must read several rows before deciding, and SERIALIZABLE with retries when the logic is too complex to express in one statement.
How much maths do I need?
Multiplication and unit conversion. The hard part is not the arithmetic but remembering to do it, and remembering that a byte is eight bits. Keep three numbers in your head: a day is 86,400 seconds, a million seconds is about twelve days, and peak traffic is roughly five times average.
Should I say “I don’t know”?
Yes, followed by how you would find out or what you would choose provisionally and why. Inventing a confident wrong answer fails the technical-judgment dimension far more decisively than admitting a gap, and interviewers are specifically watching for whether you can be honest about uncertainty — because that is what they need from you on a Tuesday.
Do I need AWS experience to learn this?
No. Everything in this article was done on one laptop with PostgreSQL and Python. Managed services are conveniences layered over concepts — a load balancer, a cache, object storage — and the concepts are what you are examined on. Learn the concept, then the service name is a footnote.
Why did SERIALIZABLE only sell one room?
Because it was working correctly and I deliberately left out the retry loop. PostgreSQL detected that 49 of the 50 transactions could not be proven equivalent to any serial order and aborted them with SQLSTATE 40001. Serializable converts a silent correctness bug into a loud, retryable error; the retry is the application’s responsibility. With retries added, it sold exactly 10.
Reproduce the lab
Every number in Part 8 came from two Python scripts against a throwaway PostgreSQL cluster. Nothing here touches a system database, and the whole thing takes about a minute.
# Debian/Ubuntu/Kali: PostgreSQL 18 and the Python driver
sudo apt install postgresql-18 python3-psycopg2
# a throwaway cluster in /tmp, on a non-default port, owned by you
export PATH=/usr/lib/postgresql/18/bin:$PATH
mkdir -p /tmp/sdlab/sock
initdb -D /tmp/sdlab/data -U labuser --auth=trust -E UTF8
pg_ctl -D /tmp/sdlab/data -o "-p 54399 -k /tmp/sdlab/sock -c listen_addresses=''" \
-l /tmp/sdlab/pg.log start
# the race, then the fixes (five trials each)
python3 lab-part1-race.py # naive, FOR UPDATE, SERIALIZABLE without retries
python3 lab-part2-fixes.py # atomic claim, SERIALIZABLE with retries, idempotency
# tear it down
pg_ctl -D /tmp/sdlab/data stop && rm -rf /tmp/sdlabThe scripts set DSN at the top; change the socket path there if you put the cluster elsewhere. Both release all 50 threads from a threading.Barrier so they contend genuinely, re-create the schema before every trial, and read the row count back from the table rather than trusting what the clients reported — which matters, because in the naive runs the clients and the table disagree, and the table is right.
Then change something. Raise the think time from 20 ms to 300 ms and watch FOR UPDATE become unusable. Drop the rooms to 2. Raise the guests to 500. The numbers in Table 5 are from my laptop; yours will differ in the milliseconds and will not differ at all in the row counts, which is the part that matters.
lab-part1-race.py
The race itself: the naive check-then-insert, then SELECT … FOR UPDATE, then SERIALIZABLE without a retry loop. THINK is the work in the gap; raise it and watch the numbers move.
import psycopg2, threading, time, json, statistics, sys
L="/tmp/claude-1000/-home-arun/80d50455-a3c4-4876-919f-9175ef1cf4c6/scratchpad/sdlab"
DSN=dict(host=f"{L}/sock", port=54399, user="labuser", dbname="postgres")
DDL = """
DROP TABLE IF EXISTS reservation; DROP TABLE IF EXISTS room_type;
CREATE TABLE room_type (
id int PRIMARY KEY, hotel text NOT NULL, name text NOT NULL, total_rooms int NOT NULL);
CREATE TABLE reservation (
id bigserial PRIMARY KEY,
room_type_id int NOT NULL REFERENCES room_type(id),
guest text NOT NULL, stay_date date NOT NULL,
idem_key text, created_at timestamptz DEFAULT clock_timestamp());
INSERT INTO room_type VALUES (1,'Hotel Annapurna','Deluxe double',10);
"""
def reset():
c=psycopg2.connect(**DSN); c.autocommit=True
with c.cursor() as cur: cur.execute(DDL)
c.close()
def count_res():
c=psycopg2.connect(**DSN)
with c.cursor() as cur:
cur.execute("SELECT count(*) FROM reservation WHERE room_type_id=1 AND stay_date='2026-12-25'")
n=cur.fetchone()[0]
c.close(); return n
TOTAL=10
STAY="2026-12-25"
def worker(mode, guest, think, results, barrier):
try:
c=psycopg2.connect(**DSN)
except Exception as e:
results.append(("connerr",str(e))); return
try:
barrier.wait() # all guests press Book at the same instant
with c:
with c.cursor() as cur:
if mode=="serializable":
cur.execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")
if mode=="forupdate":
cur.execute("SELECT total_rooms FROM room_type WHERE id=1 FOR UPDATE")
total=cur.fetchone()[0]
else:
cur.execute("SELECT total_rooms FROM room_type WHERE id=1")
total=cur.fetchone()[0]
cur.execute("SELECT count(*) FROM reservation WHERE room_type_id=1 AND stay_date=%s",(STAY,))
taken=cur.fetchone()[0]
if think: time.sleep(think) # the gap: app logic, payment call, network
if taken < total:
cur.execute("INSERT INTO reservation(room_type_id,guest,stay_date) VALUES (1,%s,%s)",(guest,STAY))
results.append(("booked",guest))
else:
results.append(("full",guest))
except psycopg2.Error as e:
results.append(("error", e.pgcode))
finally:
c.close()
def run(mode, n=50, think=0.0):
reset()
results=[]; barrier=threading.Barrier(n)
ts=[threading.Thread(target=worker,args=(mode,f"guest-{i:02d}",think,results,barrier)) for i in range(n)]
t0=time.perf_counter()
for t in ts: t.start()
for t in ts: t.join()
wall=time.perf_counter()-t0
booked=sum(1 for r in results if r[0]=="booked")
full=sum(1 for r in results if r[0]=="full")
errs=[r[1] for r in results if r[0]=="error"]
rows=count_res()
return dict(mode=mode, clients=n, think_ms=round(think*1000,1), rows_in_db=rows,
capacity=TOTAL, oversold=max(0,rows-TOTAL), said_booked=booked, said_full=full,
errors=len(errs), error_codes=sorted(set(errs)), wall_ms=round(wall*1000,1))
out={"pg_version":None,"runs":[]}
c=psycopg2.connect(**DSN)
with c.cursor() as cur:
cur.execute("show server_version"); out["pg_version"]=cur.fetchone()[0]
cur.execute("show transaction_isolation"); out["default_isolation"]=cur.fetchone()[0]
c.close()
TRIALS=5
for mode,think in [("naive",0.0),("naive",0.020),("forupdate",0.020),("serializable",0.020)]:
trials=[run(mode,50,think) for _ in range(TRIALS)]
agg=dict(mode=mode, think_ms=trials[0]["think_ms"], trials=TRIALS,
rows=[t["rows_in_db"] for t in trials],
oversold=[t["oversold"] for t in trials],
errors=[t["errors"] for t in trials],
error_codes=sorted({c for t in trials for c in t["error_codes"]}),
wall_ms=[t["wall_ms"] for t in trials])
agg["rows_median"]=statistics.median(agg["rows"])
agg["wall_median_ms"]=statistics.median(agg["wall_ms"])
out["runs"].append(agg)
print(json.dumps(agg), flush=True)
json.dump(out, open(f"{L}/results-part1.json","w"), indent=1)lab-part2-fixes.py
The fixes: the atomic claim held inside the transaction, the atomic claim committed first, SERIALIZABLE with retries, and the two double-submit runs.
import psycopg2, threading, time, json, statistics
L="/tmp/claude-1000/-home-arun/80d50455-a3c4-4876-919f-9175ef1cf4c6/scratchpad/sdlab"
DSN=dict(host=f"{L}/sock", port=54399, user="labuser", dbname="postgres")
TOTAL=10; STAY="2026-12-25"; THINK=0.020
DDL = """
DROP TABLE IF EXISTS reservation; DROP TABLE IF EXISTS room_type;
CREATE TABLE room_type (
id int PRIMARY KEY, hotel text NOT NULL, name text NOT NULL,
total_rooms int NOT NULL, booked int NOT NULL DEFAULT 0);
CREATE TABLE reservation (
id bigserial PRIMARY KEY,
room_type_id int NOT NULL REFERENCES room_type(id),
guest text NOT NULL, stay_date date NOT NULL,
idem_key text UNIQUE, created_at timestamptz DEFAULT clock_timestamp());
INSERT INTO room_type(id,hotel,name,total_rooms) VALUES (1,'Hotel Annapurna','Deluxe double',10);
"""
def reset():
c=psycopg2.connect(**DSN); c.autocommit=True
with c.cursor() as cur: cur.execute(DDL)
c.close()
def rows():
c=psycopg2.connect(**DSN)
with c.cursor() as cur:
cur.execute("SELECT count(*) FROM reservation WHERE room_type_id=1 AND stay_date=%s",(STAY,))
n=cur.fetchone()[0]
c.close(); return n
def w_atomic(guest,res,bar):
"""Claim the room in ONE atomic statement, THEN do the slow work."""
c=psycopg2.connect(**DSN)
try:
bar.wait()
with c:
with c.cursor() as cur:
cur.execute("UPDATE room_type SET booked=booked+1 WHERE id=1 AND booked < total_rooms RETURNING booked")
got=cur.fetchone()
if not got: res.append(("full",guest)); return
time.sleep(THINK) # payment / email / slow work, lock already released? no: same txn
cur.execute("INSERT INTO reservation(room_type_id,guest,stay_date) VALUES (1,%s,%s)",(guest,STAY))
res.append(("booked",guest))
except psycopg2.Error as e: res.append(("error",e.pgcode))
finally: c.close()
def w_atomic_short(guest,res,bar):
"""Claim in its own tiny transaction; slow work happens outside the lock."""
c=psycopg2.connect(**DSN); c.autocommit=True
try:
bar.wait()
with c.cursor() as cur:
cur.execute("UPDATE room_type SET booked=booked+1 WHERE id=1 AND booked < total_rooms RETURNING booked")
if not cur.fetchone(): res.append(("full",guest)); return
time.sleep(THINK) # outside any transaction
with c.cursor() as cur:
cur.execute("INSERT INTO reservation(room_type_id,guest,stay_date) VALUES (1,%s,%s)",(guest,STAY))
res.append(("booked",guest))
except psycopg2.Error as e: res.append(("error",e.pgcode))
finally: c.close()
def w_serial_retry(guest,res,bar,maxtry=25):
c=psycopg2.connect(**DSN); tries=0
try:
bar.wait()
while tries<maxtry:
tries+=1
try:
with c:
with c.cursor() as cur:
cur.execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")
cur.execute("SELECT total_rooms FROM room_type WHERE id=1")
total=cur.fetchone()[0]
cur.execute("SELECT count(*) FROM reservation WHERE room_type_id=1 AND stay_date=%s",(STAY,))
taken=cur.fetchone()[0]
time.sleep(THINK)
if taken<total:
cur.execute("INSERT INTO reservation(room_type_id,guest,stay_date) VALUES (1,%s,%s)",(guest,STAY))
res.append(("booked",guest,tries)); return
res.append(("full",guest,tries)); return
except psycopg2.Error as e:
if e.pgcode=="40001": continue
res.append(("error",e.pgcode,tries)); return
res.append(("gaveup",guest,tries))
finally: c.close()
def run(fn,n=50,trials=5):
agg=[]
for _ in range(trials):
reset(); res=[]; bar=threading.Barrier(n)
ts=[threading.Thread(target=fn,args=(f"guest-{i:02d}",res,bar)) for i in range(n)]
t0=time.perf_counter()
for t in ts: t.start()
for t in ts: t.join()
wall=(time.perf_counter()-t0)*1000
r=rows()
agg.append(dict(rows=r, oversold=max(0,r-TOTAL), wall_ms=round(wall,1),
booked=sum(1 for x in res if x[0]=="booked"),
full=sum(1 for x in res if x[0]=="full"),
errors=sum(1 for x in res if x[0]=="error"),
retries=sum((x[2]-1) for x in res if len(x)>2 and isinstance(x[2],int))))
return agg
out={}
for name,fn in [("atomic_claim_in_txn",w_atomic),("atomic_claim_short_txn",w_atomic_short),("serializable_retry",w_serial_retry)]:
a=run(fn)
s=dict(mode=name, rows=[x["rows"] for x in a], oversold=[x["oversold"] for x in a],
wall_ms=[x["wall_ms"] for x in a], errors=[x["errors"] for x in a],
retries=[x["retries"] for x in a],
rows_median=statistics.median(x["rows"] for x in a),
wall_median_ms=statistics.median(x["wall_ms"] for x in a))
out[name]=s; print(json.dumps(s), flush=True)
# --- idempotency: one guest double-submits the same request 20 times concurrently
def w_idem(i,res,bar,key):
c=psycopg2.connect(**DSN); c.autocommit=True
try:
bar.wait()
with c.cursor() as cur:
cur.execute("""INSERT INTO reservation(room_type_id,guest,stay_date,idem_key)
VALUES (1,'guest-impatient',%s,%s)
ON CONFLICT (idem_key) DO NOTHING RETURNING id""",(STAY,key))
r=cur.fetchone()
res.append("created" if r else "deduped")
except psycopg2.Error as e: res.append("err:"+str(e.pgcode))
finally: c.close()
def w_noidem(i,res,bar,key):
c=psycopg2.connect(**DSN); c.autocommit=True
try:
bar.wait()
with c.cursor() as cur:
cur.execute("INSERT INTO reservation(room_type_id,guest,stay_date) VALUES (1,'guest-impatient',%s)",(STAY,))
res.append("created")
except psycopg2.Error as e: res.append("err:"+str(e.pgcode))
finally: c.close()
for name,fn in [("double_submit_no_key",w_noidem),("double_submit_idem_key",w_idem)]:
tot=[]
for t in range(5):
reset(); res=[]; bar=threading.Barrier(20)
ts=[threading.Thread(target=fn,args=(i,res,bar,"req-7f3a2c")) for i in range(20)]
for x in ts: x.start()
for x in ts: x.join()
tot.append(dict(clicks=20, rows=rows(), created=res.count("created"), deduped=res.count("deduped")))
out[name]=tot; print(name, json.dumps(tot), flush=True)
json.dump(out, open(f"{L}/results-part2.json","w"), indent=1)References
- Hayk Simonyan, Design Software Systems Like a Senior Engineer – Complete Course, freeCodeCamp.org, 13 October 2026 (3 h 16 m). The five-step framework, the five scored dimensions, the pyramid, and the Spotify, Booking.com and WhatsApp walkthroughs.
- PostgreSQL 18 documentation, “Transaction Isolation”. The levels, what each permits, and why serialisation failures must be retried by the application.
- PostgreSQL 18 documentation, “Explicit Locking”.
FOR UPDATEand row-level lock behaviour. - MySQL 8.4 reference manual, InnoDB transaction isolation levels. For the
REPEATABLE READdefault mentioned in the exam answers. - Lab measurements: PostgreSQL 18.6 (Debian 18.6-3) on Linux 7.1.5, Python 3 with psycopg2, 50 threads, five trials per variant, 1 November 2026. The two scripts are reproduced in full above, and the raw JSON results are quoted in Tables 5 to 7.
Related reading on CSSNepal
- The CAP theorem, properly, and why PACELC matters more — the consistency and availability trade-offs in Part 4, proved and then measured on real clusters. Read this next.
- DBMS explained: keys, relationships, the ER model and normalization — the foundation under Part 7, if the schema section moved quickly.
- NoSQL databases explained — the alternative you should be able to argue against when you choose SQL.
- The CSSNepal SQL Lab — run the queries from Part 7 in your browser, nothing to install.
If you build the lab and get a different result, or you think one of the fixes is wrong for a case I have not considered, write it in the comments with your numbers. That argument is the subject.
