A mock round is a rehearsal under the real conditions: a prompt you have not seen, a clock, and no notes. Its value comes from the gap between what you said and what a strong answer contains, so you need a way to measure that gap.
Each of the four prompts that follow is built the same way. You get the prompt, the assumptions that a person asking questions would have given you, and a time box of 45 minutes. Set a timer, draw on paper or a whiteboard, and speak your answer aloud, to a friend if you can, to a wall if you cannot. Do not open the model answer until the timer ends. Then read it, mark what you missed, and score yourself.
Use the budget from the interview chapter as your clock: 5 minutes for requirements, 5 for estimates, 7 for the API and data model, 10 for the high-level design, 13 for the deep dives and 5 for the wrap-up. The prompts below give you the assumptions up front, so you save the time you would have spent asking, and you can spend it on the design.
Minutes
Step
Output you should have on the page
0 to 5
Requirements
Three to five functional requirements, two to four numbers for quality, and what is out of scope
5 to 10
Estimates
Requests a second at the peak, storage, and the one number that will drive the design
10 to 17
API and data model
The few calls and the main tables with their keys
17 to 27
High-level design
One request traced through the parts, in order
27 to 40
Deep dives
The two hardest parts in detail, with the failure of each
40 to 45
Wrap-up
What fails, what you gave up, what comes next
The rubric
Score yourself from 1 to 4 on six lines. The lines are the ones the interview chapter named: requirements, estimates, design, deep dive, trade-offs and communication. Be strict. A 3 is a good answer, and a 4 should be rare.
Line
1
2
3
4
Requirements
Starts drawing at once
Lists features only
Features and numbers for quality
Also states what is out of scope and what could change the design
Estimates
None, or a number with no basis
Numbers, but they never change the design
Peak rates and sizes with stated assumptions
Finds the one number that drives the design and says so
Design
A list of products
Parts with no flow between them
One request traced through every part
Also traces the write path and the failure path
Deep dive
Stays shallow everywhere
Goes deep on an easy part
Goes deep on a hard part
Goes deep on two hard parts, with their failures
Trade-offs
None named
Named but not costed
Each choice with what it gives up
Costs a choice in numbers and says when it would change
Communication
Silent or scattered
Clear but jumpy
Follows the steps and checks in
Also summarises at each step and adapts to a changed constraint
Requirements
1Starts drawing at once
2Lists features only
3Features and numbers for quality
4Also states what is out of scope and what could change the design
Estimates
1None, or a number with no basis
2Numbers, but they never change the design
3Peak rates and sizes with stated assumptions
4Finds the one number that drives the design and says so
Design
1A list of products
2Parts with no flow between them
3One request traced through every part
4Also traces the write path and the failure path
Deep dive
1Stays shallow everywhere
2Goes deep on an easy part
3Goes deep on a hard part
4Goes deep on two hard parts, with their failures
Trade-offs
1None named
2Named but not costed
Add the six scores. The bands are this course's own and not a company's: 6 to 11 means a step is missing and should be practised alone, 12 to 17 is a solid answer with gaps, and 18 to 24 is an answer you could give on the day. Write down the six scores and the one line you will work on. A row of scores over several prompts shows a pattern that a single round hides.
Learning from the model answers
The model answers are one good answer each. They are not the only one. Your design can differ in its parts and still score a 4, as long as each choice follows from a number or a requirement and has its cost named.
When you compare, look for three kinds of gap. A gap in content means you missed a part, such as a failure path. A gap in numbers means your estimate did not drive a choice. A gap in order means you had the right ideas but said them in a way that was hard to follow. The first is cured by rereading the chapter on that block. The second by doing the estimate again with a different assumption and seeing what changes. The third only by saying the answer aloud again.
The prompts avoid the products of the case chapters. They reuse the same blocks in new combinations, because that is what a new question does. After the four, make up a fifth for yourself from something you use every day, give it assumptions, and run it against the clock.
Why do the prompts give you assumptions instead of leaving you to ask?
It saves minutes in the 45-minute box and lets everyone check an answer against the same numbers.
In a real round you would ask for them, which is the first step of the method.
You score 3, 3, 4, 2, 2, 3. What do you do next?
The total is 17, a solid answer with gaps. Work on the lowest lines, the deep dive and the trade-offs.
Redo one prompt a week later and compare the six scores.
Your design differs from the model answer. Is that a problem?
Not by itself. Each choice must follow from a requirement or a number and have its cost named.
Check the gaps in content, numbers and order.
Part 2 · Prompt 1: train ticket booking at the 10 am rush
The prompt and the clock
Prompt. A state railway opens advance booking for tomorrow's trains at 10 am every day. Design the website's booking system so that it stays up and never sells a seat twice. You have 45 minutes.
Assumptions (invented for the drill): 8 lakh users are on the site at 10:00:00. In the first five minutes each makes 20 reads, such as searching trains and checking availability. A quarter of the users try to book once. A hot train class, the pair of a train and a date and a class such as sleeper, is read from a set of 20,000 such rows. A seat is held for about two minutes on average while the passenger pays through an outside payment provider.
Out of scope: refunds, waiting lists, choosing a berth and the provider's internals.
python
# Assumptions for the drill (all invented, all stated in the answer)
online = 8_00_000 # users on the site at 10:00:00
window = 300# the first five minutes, in seconds
reads_each = 20# search and availability reads per user
tryers = 0.25# share of users who try to book
holds_each = 1# booking attempts per trying user
hot_keys = 20_000 # (train, date, class) rows that get read
ttl = 2# seconds an availability answer is cached
reads = online * reads_each / window
print(f"availability reads : {reads:>9,.0f} a second on average")
print(f" with a {ttl} s cache : at most {hot_keys / ttl:>7,.0f} "
f"a second reach the store")
attempts = online * tryers * holds_each
rate = attempts / window
print(f"booking attempts : {attempts:>9,.0f} in {window} s, "
f"{rate:,.0f} a second")
print(f" peak at 3x : {rate * 3:>9,.0f} a second")
hold_secs = 120# average time a seat is held while paying
print(f"seats held at once : {rate * hold_secs:>9,.0f} "
f"({hold_secs} s average hold)")
text
availability reads : 53,333 a second on average
with a 2 s cache : at most 10,000 a second reach the store
booking attempts : 200,000 in 300 s, 667 a second
peak at 3x : 2,000 a second
seats held at once : 80,000 (120 s average hold)
The reads, 53,333 a second, are cacheable. With answers cached for 2 seconds, at most 10,000 a second reach the store, because each of the 20,000 rows is fetched once per two seconds at most. The writes are the real problem: 2 lakh booking attempts in 300 seconds is 667 a second, 2,000 at a peak of three times, and about 80,000 seats are held at any moment. The number that drives the design is the booking attempts, because each one must change shared inventory correctly.
Model answer: from requirements to the design
Requirements. Functional: search trains by route and date, see availability by class, hold seats for up to six passengers, pay, receive a ticket. Non-functional: a seat is never sold twice, which is a correctness requirement; reads are fast; an attempt that was started either confirms or gives its seats back; the site survives the first five minutes.
Data model. An inventory row per train, date and class with a count of seats left, and a hold table with the row, the number of seats, an expiry and a state. A booking table with the hold, the passengers and the payment reference, in the states held, paid, confirmed and expired.
Design, in request order. Page files come from a CDN. Availability reads go to a cache with a 2-second lifetime, and when an entry expires only one request refreshes it while the others wait, the single-flight rule of the cache chapter, so a popular train does not cause a stampede on the store. A waiting room stands in front of booking: a user who asks to book receives a place in a queue and is let in at a fixed rate, set to what the booking service and the payment provider can take. It works like the rate limiter chapter's bucket, except that the excess waits and is not refused.
An admitted user reaches a stateless booking service. It takes a seat with one conditional statement on the inventory row, in the style of the claim in the task scheduler chapter: reduce the count by the number of seats where the count is at least that number. If the statement changes no row, the seats are gone, and the user is told at once. If it succeeds, the service writes a hold with an expiry and sends the user to pay.
Animated sceneBooking at the 10 am rush0:26
Watch for the waiting room: reads are cached, but booking is let in slowly
Read it as steps
A waiting room limits how many users reach booking, and seats are taken in the database.
The cache absorbs the reads and the waiting room meters the writes.
Model answer: deep dives and trade-offs
Deep dive 1: the hold and its expiry. A hold is a lease, as in the task scheduler chapter. If the user closes the tab, the seats must come back. A recurring sweep finds holds past their expiry that are still held, marks them expired and adds their seats back to the inventory in one transaction. The payment step carries an idempotency key made from the hold id, so a double click or a retry does not charge twice. If the payment arrives after the hold expired, the service checks the inventory: if the seats are still free it confirms, and if not it refunds.
Deep dive 2: the hot inventory row. A popular train class takes many attempts, and every one updates the same row. The updates queue behind each other, so the row can become the limit before the servers do. Measure it. If it is, split the count into a few shard rows, as the sharded counter chapter does for likes, and have each attempt try one shard first. The cost is that the last few seats are spread over shards, so an attempt that finds its shard empty must try the others.
Trade-offs. The cache shows a seat as free for up to two seconds after it is gone, so some users will fail at the booking step. That is acceptable, since the inventory update is the only authority, and it is cheaper than asking the store on every read. The waiting room is fair and predictable, at the cost of a wait. The inventory is the one part that needs strong consistency, so it lives in a single primary database with a synchronous replica: a confirmed hold then survives a failover, and each write waits for the replica.
Failure. The update and the hold are written in one transaction, so a crash between them cannot lose seats.
Score yourself
Line
A 4 on this prompt includes
Requirements
Never sells a seat twice as a requirement, and refunds and waiting lists as out of scope
Estimates
Reads cached to about 10,000 a second, and 667 attempts a second as the driving number
Design
CDN, cache, waiting room, booking service and inventory, and the path of a payment
Deep dive
The hold with its expiry, and the hot row with a way out
Trade-offs
Stale availability, hold length, and strong consistency only for inventory
Communication
Says the driving number early and returns to it
Why is the number of booking attempts, and not the number of reads, the driving number?
Reads can be cached for 2 seconds, which caps the store at about 10,000 a second.
Each of the 667 attempts a second must change shared inventory correctly, and cannot be cached.
A user closes the tab while holding two seats. What brings the seats back?
A recurring sweep finds holds past their expiry and still held, marks them expired and returns the seats in one transaction.
The hold is a lease.
The payment succeeds after the hold has expired. What does the service do?
It checks the inventory. If the seats are still free it confirms the booking, and if not it refunds.
Reconciliation with the provider's records catches the rest.
Part 3 · Prompt 2: a notification service for push, SMS and email
The prompt and the clock
Prompt. Design a service that other teams in a company call to notify a user by push, SMS or email, for example that an order has shipped. It must not send the same message twice by mistake, must respect each user's choices, and must keep urgent messages from waiting behind a marketing campaign. You have 45 minutes.
Assumptions: 2 crore users, 3 notifications a user a day, of which 70% go by push, 20% by email and 10% by SMS. A marketing team wants to send one push to 50 lakh users within 10 minutes. The SMS provider accepts 500 messages a second.
python
# Assumptions for the drill (all invented, all stated in the answer)
users = 2_00_00_000 # 2 crore registered users
per_user_day = 3# notifications per user per day
share = {"push": 0.70, "email": 0.20, "sms": 0.10}
campaign = 50_00_000 # one marketing push to 50 lakh users
campaign_mins = 10# the team wants it delivered in 10 minutes
per_day = users * per_user_day
print(f"per day : {per_day:,} notifications, "
f"{per_day / 86_400:,.0f} a second on average")
for ch, f in share.items():
print(f" {ch:<5} : {per_day * f:>12,.0f} a day")
rate = campaign / (campaign_mins * 60)
print(f"campaign burst : {rate:,.0f} a second "
f"for {campaign_mins} min")
sms_cap = 500# assumed SMS provider limit, a second
hours = per_day * share["sms"] / sms_cap / 3600
print(f"sms send time : {hours:.1f} h a day at {sms_cap} a second")
text
per day : 60,000,000 notifications, 694 a second on average
push : 42,000,000 a day
email : 12,000,000 a day
sms : 6,000,000 a day
campaign burst : 8,333 a second for 10 min
sms send time : 3.3 h a day at 500 a second
The average, 694 a second, is small. The campaign is the load that matters: 8,333 a second for ten minutes, twelve times the average. SMS is the scarce channel, at 60 lakh a day, which at the provider's limit is 3.3 hours of sending a day, so a burst of urgent SMS can queue behind bulk SMS if they share one line. That is the number that decides the shape of the queues.
The API
The calling teams need one call to send and one to read the result. Each send carries an idempotency key, a value that the caller chooses and repeats on a retry, so that a retried call after a timeout does not send a second message. The sketch is below. The calls after it were run against a small stub server that keeps the keys in a dictionary, on this machine.
The script sends the call, repeats it with the same key, sends it with a new key, and reads the status of the first notification. The first call shows the response headers.
bash
URL=http://127.0.0.1:55492/v1/notifications
H="Content-Type: application/json"
BODY='{"user_id": "u_1042", "template": "order_shipped",
"channels": ["push", "sms", "email"], "vars": {"order": "A1001"}}'
send() { # send KEY: post the notification with that idempotency key
curl -s "${@:2}" -X POST "$URL" -H "Idempotency-Key: $1" \
-H "$H" -d "$BODY"
echo
}
echo "--- first request, with headers"; send ship-A1001 -i
echo "--- same key again"; send ship-A1001
echo "--- new key"; send ship-A1002
echo "--- status of n_1"
curl -s "$URL/n_1" | python -m json.tool --indent 2
text
--- first request, with headers
HTTP/1.0202 Accepted
Server: BaseHTTP/0.6 Python/3.12.10
Date: Sun, 22 Nov 202615:05:27 GMT
Content-Type: application/json
Content-Length: 35
{"id": "n_1", "status": "accepted"}
--- same key again
{"id": "n_1", "status": "accepted"}
--- new key
{"id": "n_2", "status": "accepted"}
--- status of n_1
{
"id": "n_1",
"channels": {
"push": "queued",
"sms": "queued",
"email": "queued"
}
}
The service answers 202, which means accepted and not yet delivered, with an id to ask about later. The repeat with the key ship-A1001 returned n_1 again and sent nothing more, and a new key returned n_2. The status shows one entry per channel, all queued. The stub keeps the keys in memory, and a real service stores them in a database with an expiry.
Model answer: the pipeline
Requirements. Functional: send by template to one or many users on one or more channels, respect opt-outs, report the status per channel. Non-functional: no duplicate sends from retries, urgent messages in seconds, bulk messages as fast as the providers allow, and a record of what was sent.
Design, in order. The API validates the call, checks the idempotency key, and stores the notification with one row per channel. It then checks the user's preferences: a user who has turned off marketing push gets none, and a message that falls in the user's quiet hours is delayed with a scheduled task, as in the task scheduler chapter, in the user's time zone. The service renders the template and puts one job per channel on a queue.
There are separate queues for urgent and bulk traffic. Urgent covers codes, receipts and alerts, and bulk covers campaigns. Workers for the urgent queue are never lent to bulk, so a campaign of 50 lakh cannot delay a receipt. This is the priority and fairness idea of the task scheduler chapter, applied with two classes. Within bulk, each sending team gets a fair share, so one team's campaign does not starve another's.
Channel workers take a job and call a provider through an adapter, one adapter per channel and provider. Each adapter has its own limit, a token bucket set just below the provider's rate, 500 a second for SMS, so the system waits in its own queue and never gets refused by the provider. Failures retry with backoff and jitter. A job that fails several times goes to a dead-letter queue, and for urgent messages the worker may try the next channel in the user's list, for example SMS when push has no valid token.
Model answer: deep dives and trade-offs
Deep dive 1: no duplicate sends. The queues deliver at least once, so a worker can send and crash before it acknowledges, and the job comes back. The adapter therefore uses a key per notification and channel, such as the notification id with the channel name, and records it before or with the send. Where the provider accepts such a key, the adapter passes it on. Where it does not, a crash between the send and the record can still repeat a message, and the design accepts that rare repeat for the sake of never losing one.
Deep dive 2: the campaign. A campaign to 50 lakh users is not one request. It is a scheduled task that expands the audience in pages of, say, a few thousand users, creating the per-user jobs for each page and remembering how far it got, so a crash resumes from the last page. The jobs enter the bulk queue at the pace the providers allow. With 8,333 a second the push part takes the 10 minutes the team asked for only if the push provider can take that rate. If it cannot, the plan says how long the campaign will take rather than pretending.
Receipts. Providers report delivery later, often by calling a webhook. The webhook handler updates the channel's state from sent to delivered or failed, and it must be idempotent too, since providers retry their calls. Status per channel is queued, sending, sent, delivered, failed.
Trade-offs. At-least-once with keys favours never losing a message over never repeating one. Separate urgent and bulk queues cost extra workers that sit idle at quiet times. SMS fallback improves delivery and costs money, so it is limited to urgent messages. A per-user cap on marketing messages protects users and costs the marketing team some reach.
Score yourself
Line
A 4 on this prompt includes
Requirements
No duplicates, respect for choices, urgent against bulk, status per channel
Estimates
694 a second on average, the 8,333 a second burst, and SMS as the scarce channel
Design
API, preferences, queues per class, adapters with limits, and receipts
Deep dive
Duplicate prevention with keys, and a resumable campaign
Trade-offs
Duplicates against loss, idle capacity, SMS cost, and per-user caps
Communication
Names the urgent and bulk split as the main idea early
Why do urgent and bulk messages use separate queues and workers?
A campaign of 50 lakh would otherwise delay codes and receipts that sit behind it.
Workers for the urgent queue are never lent to bulk.
A caller times out and sends the same request again. How does the service avoid a second message?
The caller sends the same idempotency key, and the service returns the first result without sending again.
In the run, the repeat with the key ship-A1001 returned n_1 again.
Why is a campaign to 50 lakh users handled as a scheduled task that works in pages?
It can remember where it stopped, so a crash resumes from the last page without sending again.
It also feeds the queue at the rate the providers allow.
Part 4 · Prompt 3: live order tracking for food delivery
The prompt and the clock
Prompt. Design the live tracking screen of a food delivery app. A customer who has ordered sees the rider moving on a map and the status of the order: placed, accepted, preparing, picked up, delivered. You have 45 minutes.
Assumptions: 1.5 lakh riders are online at the evening peak, each sending a location every 5 seconds. 1 lakh orders are on the road, and each is watched by 1.5 devices on average. One server can hold 50,000 open connections, an assumed figure to be checked, not a measured one.
python
# Assumptions for the drill (all invented, all stated in the answer)
riders = 1_50_000 # riders sending their location at once
ping_secs = 5# one location update per rider each 5 s
ping_bytes = 80# id, latitude, longitude, time, sequence
orders = 1_00_000 # orders on the road right now
viewers_each = 1.5# devices watching each order
per_server = 50_000 # open connections one server can hold
writes = riders / ping_secs
print(f"location writes : {writes:,.0f} a second, "
f"{writes * ping_bytes / 1e6:.1f} MB a second")
print(f"latest positions : {riders * 100 / 1e6:.0f} MB "
f"for {riders:,} riders at 100 bytes each")
viewers = orders * viewers_each
print(f"watching devices : {viewers:,.0f}")
print(f"if they poll : {viewers / ping_secs:,.0f} reads a second")
servers = -(-viewers // per_server)
print(f"if we push : {viewers:,.0f} connections, "
f"{servers:,.0f} servers at {per_server:,} each")
text
location writes : 30,000 a second, 2.4 MB a second
latest positions : 15 MB for 150,000 riders at 100 bytes each
watching devices : 150,000
if they poll : 30,000 reads a second
if we push : 150,000 connections, 3 servers at 50,000 each
The writes are the big number: 30,000 location updates a second, at 2.4 MB a second, which is small in bytes and large in count. The store of latest positions is 15 MB, tiny. The reads depend on the delivery method. 1.5 lakh watching devices polling every 5 seconds make 30,000 reads a second. Holding the same devices on open connections takes 3 servers by the assumed capacity. Both are manageable.
Model answer: ingest and store
Requirements. Functional: show the rider's position, update it every few seconds, show the order status and an estimated arrival time from a routing service, as in the maps chapter. Non-functional: updates reach the customer within a few seconds, an old position never overwrites a newer one, and location is shown only while the order is active.
Ingest. The rider app sends a small message with the rider id, a position, a time and a sequence number that increases by one with each message. A load balancer spreads these over stateless ingest servers, which validate the message and write it into a stream, a log of messages that other services read. The log decouples the 30,000 writes a second from everything that uses them, as the message queue and pub-sub chapters describe.
Store. Two things are kept. The latest position of each rider lives in a key-value store, keyed by rider id, and each write overwrites the last. The store holds 15 MB, so it is cheap and fast, and it can expire a key a few minutes after the rider's last message. The history is written from the stream in batches to cheaper storage, sampled to one point in several, for support questions and for estimating arrival times later. Only the latest position is on the live path.
The order status is separate. It is a small state machine in the order service, written when the restaurant or the rider changes it, and it is the slow-moving part of the screen. It rarely changes, so it is cached and refreshed when an event arrives.
Model answer: reaching the customer
Delivery to the screen. The tracking service holds a map from each active order to its rider and to the devices watching it. When a new position for a rider arrives from the stream, the service finds the watching devices and sends the position to them. This fan-out is one to one or one to two, so there is no celebrity problem, unlike a feed, and the load is the 30,000 updates a second multiplied by the share that have a watcher.
There are two ways to deliver. Polling: each device asks every 5 seconds for the latest position. That is 30,000 reads a second of a tiny value, served from the key-value store and a short cache. It is simple, and it survives a server loss because every request stands alone. Push: each device keeps a connection open, a WebSocket or a stream of server-sent events, and the server sends a position when it changes. By the assumed capacity that is 3 servers, and updates arrive as soon as they exist. Its cost is state: a lost connection server drops its devices, which reconnect and ask for the latest position first, then continue.
A sound answer picks one and says why. Push fits here, because an update is useful only if it is fresh and the connection count is modest, and polling is a fair first version. Either way the first message after a connect or poll is the latest stored position, so a reconnecting client is never blank.
Ordering and bad networks. Messages from a rider can arrive late or twice. The sequence number lets the store ignore any position older than the one it holds, so the last writer by sequence wins and not by arrival. If the rider vanishes, the customer's screen shows the last position with its age, and after a threshold a message that the rider's location is unavailable.
Deep dive and trade-offs
Deep dive: load shedding on the live path. If the stream or the store falls behind, old positions are worthless: only the newest matters. So the live path drops old messages instead of queueing them. A consumer that is behind skips to the newest position per rider. This is the opposite of an order queue, where every message counts, and it is the key difference between telemetry and transactions. The history path, which needs every point, reads the same stream separately, at its own pace.
Privacy. A rider's position is personal data. Only the customer who owns an active order may see its rider, the screen checks that on every connection, and the feed stops when the order is delivered.
Trade-offs. Updating every 5 seconds gives a smooth map and 30,000 writes a second. Updating every 10 would halve the load and make the marker jump. Push gives fresher positions and needs connection servers that hold state. Polling gives a little delay and no state. Drop-old-on-overload keeps the screen fresh in a spike, and it loses points that the history path must keep by other means.
Failure. If a connection server dies, its devices reconnect and receive the latest position. If the key-value store fails, the screen shows the last position it has and its age.
Score yourself
Line
A 4 on this prompt includes
Requirements
Freshness in seconds, newer never overwritten by older, and location shown only while active
Estimates
30,000 writes a second, and polling reads against open connections
Design
Ingest, stream, latest-position store, tracking service and the order status
Deep dive
Ordering by sequence, and dropping old updates under load
Trade-offs
Push against poll, update interval, and history sampling
Communication
Separates the live path from the history path
Why does the latest-position store overwrite instead of appending?
Only the newest position matters on the live screen, and an overwrite keeps the store at about 15 MB.
History is kept separately, from the same stream.
A position from 10:00:05 arrives after one from 10:00:10. What stops the old one from overwriting the newer?
The sequence number: the store ignores a position whose sequence is lower than the one it holds.
The last writer by sequence wins, not by arrival.
The live path falls behind. Why does it drop old messages and not queue them?
An old position is no longer useful, and only the newest matters to the screen.
The history path reads the same stream separately so that it keeps every point.
Part 5 · Prompt 4: a meeting-notes summariser
The prompt and the clock
Prompt. A company wants a service that takes the transcript of a finished video meeting and posts a short summary and a list of action items to the people who were there. Each action item names an owner and a due date. The service must never invent an owner or a task, and it must cope with meetings that run for hours. You have 45 minutes.
Assumptions (invented for the drill): 1 lakh meetings end each day, and the busiest hour holds 15 percent of them. An average meeting is about 6,000 words, and one in twenty is a workshop of about 24,000. The transcript arrives with the list of attendees. People should have notes within 10 minutes. The model runs on the company's own server, and no transcript may leave the network. Out of scope: recording, speech to text, calendars and editing the notes.
The script below uses the shared model server on this machine, gemma4:12b on Ollama 0.40.2, and Python 3.12.10 with only the standard library. It runs a small invented transcript through the model whole and in chunks, checks every action item in code, and sizes a day from the speeds it measured. Save the nine blocks, in order, as meeting.py.
python
import json, re, statistics, textwrap, time, urllib.request
HOST, CHAT = "http://127.0.0.1:11500", "gemma4:12b"
ATTENDEES = ["Meera", "Arjun", "Kavya", "Imran"]
LINES = [
"Meera: Let's start with the leave page. Arjun, where are we?",
("Arjun: People are logged out after two minutes. I think the ""session timeout is wrong."),
"Meera: That will upset anyone with a long reason. Can you fix it?",
("Arjun: Yes, I will fix the timeout and push it to staging by ""Thursday."),
"Kavya: The date picker also lets people choose a Sunday as leave.",
"Arjun: That is a separate bug. I will open a ticket for it today.",
"Meera: Kavya, is the approval screen design ready?",
("Kavya: Nearly. I need two more days for the mobile layout. ""I will send the design file to Imran by Friday."),
("Imran: Fine. We have only two old test phones, so I will ""book five from the device lab by Wednesday."),
"Meera: Someone should also look at the slow manager dashboard.",
("Kavya: The logs show queries taking seconds, but I do not know ""where they come from."),
"Meera: We will come back to that next week.",
"Arjun: Maybe we could try a dark mode while we are in the code.",
("Meera: Not now. Finance asked who pays for the e-signature ""licence. I will ask them and tell you all by Monday."),
"Meera: We release on the twentieth without the fix. Agreed?",
"Kavya: Agreed.",
"Imran: Agreed.",
]
TRANSCRIPT = "\n".join(LINES) + "\n"
Python 3.12.10, standard library, gemma4:12b on a local Ollama 0.40.2. Run: uv run --python 3.12 meeting.py. Part 1 of 9; save all parts in one file, meeting.py.
python
SCHEMA = {"type": "object",
"required": ["summary", "decisions", "actions"],
"properties": {
"summary": {"type": "string"},
"decisions": {"type": "array", "items": {"type": "string"}},
"actions": {"type": "array", "items": {
"type": "object",
"required": ["task", "owner", "due", "evidence"],
"properties": {"task": {"type": "string"},
"owner": {"type": ["string", "null"]},
"due": {"type": ["string", "null"]},
"evidence": {"type": "string"}}}}}}
RULES = ("Read the meeting transcript. Write a summary of at most ""three sentences, list decisions, and list action items. An action ""item is a commitment by a named person to do something. Do not ""list ideas, wishes or things nobody took on. Set owner to the ""person's name or null, due to the stated deadline or null, and ""evidence to the exact words from the transcript that make the ""commitment.")
Continues meeting.py (part 2 of 9), same file.
python
def call(system, user, schema, num_predict=700):
body = {"model": CHAT, "stream": False, "think": False,
"format": schema,
"messages": [{"role": "system", "content": system},
{"role": "user", "content": user}],
"options": {"temperature": 0, "seed": 7,
"num_predict": num_predict}}
req = urllib.request.Request(
HOST + "/api/chat", json.dumps(body).encode(),
{"Content-Type": "application/json"})
t = time.time()
with urllib.request.urlopen(req, timeout=600) as f:
r = json.load(f)
r["wall"] = time.time() - t
try:
return json.loads(r["message"]["content"]), r
except ValueError: # a reply cut off by num_predictreturnNone, r
Continues meeting.py (part 3 of 9), same file.
python
def check(actions, transcript, attendees):
"""Split the model's actions into passed and flagged."""
flat = re.sub(r"\s+", " ", transcript)
ok, bad = [], []
for a in actions:
why = []
if a["owner"] isnotNoneand a["owner"] notin attendees:
why.append("owner is not an attendee")
if re.sub(r"\s+", " ", a["evidence"]).strip() notin flat:
why.append("evidence is not in the transcript")
(bad if why else ok).append((a, why))
return ok, bad
Continues meeting.py (part 4 of 9), same file.
python
def show(label, r):
ms = lambda k: r[k] / 1e6
print(f"{label:<11}in {r['prompt_eval_count']:>4}"
f" out {r['eval_count']:>4}"
f" prefill {ms('prompt_eval_duration'):>4.0f}"
f" decode {ms('eval_duration'):>6.0f} (ms)")
def say(text):
print(textwrap.fill(text, 70, subsequent_indent=" "))
def chunks(text, limit):
"""Whole lines, at most `limit` words in each chunk."""
out, cur, n = [], [], 0for line in text.splitlines():
w = len(line.split())
if cur and n + w > limit:
out.append("\n".join(cur)); cur, n = [], 0
cur.append(line); n += w
return out + ["\n".join(cur)]
words = len(TRANSCRIPT.split())
print(f"transcript: {words} words, {len(ATTENDEES)} attendees")
Continues meeting.py (part 5 of 9), same file.
python
# 1. One call over the whole transcript.
whole, r1 = call(RULES, TRANSCRIPT, SCHEMA)
show("one call", r1)
ok, bad = check(whole["actions"], TRANSCRIPT, ATTENDEES)
say("summary: " + whole["summary"])
for a, _ in ok:
say(f" action: {a['owner']} | {a['task']} | due {a['due']}")
for a, why in bad:
print(f" FLAGGED: {a['task']} ({', '.join(why)})")
print(" decisions:", len(whole["decisions"]))
# 2. Map and reduce: notes per chunk, actions checked in code,# one summary written from the notes.
parts, stats, merged, notes = chunks(TRANSCRIPT, 80), [], {}, []
for i, part in enumerate(parts, 1):
got, r = call(RULES, part, SCHEMA)
show(f"chunk {i}/{len(parts)}", r); stats.append(r)
for a, _ in check(got["actions"], part, ATTENDEES)[0]:
merged.setdefault(a["evidence"], a)
notes.append(got["summary"])
Continues meeting.py (part 6 of 9), same file.
python
final, r = call("Write a summary of at most three sentences from ""these notes of one meeting.", "\n".join(notes),
{"type": "object", "required": ["summary"],
"properties": {"summary": {"type": "string"}}})
show("reduce", r); stats.append(r)
say("final summary: " + final["summary"])
print("chunked actions:", len(merged), "| calls:", len(stats))
# 3. What the instructions alone cost, then the rates the runs gave.
_, r0 = call(RULES, "Hello.", SCHEMA, num_predict=1)
fixed = r0["prompt_eval_count"] # instructions and framing
read = sum(s["prompt_eval_count"] for s in stats[:-1])
tok_per_word = (read - fixed * len(parts)) / words
# the middle value of the calls, so one stalled call sets no rate
rate = lambda n, d: statistics.median(
s[n] / (s[d] / 1e9) for s in stats[:-1])
prefill = rate("prompt_eval_count", "prompt_eval_duration")
decode = rate("eval_count", "eval_duration")
print(f"measured: {fixed} fixed tokens a call, "
f"{tok_per_word:.2f} tokens a word")
print(f" prefill {prefill:,.0f} tok/s, decode {decode:,.1f} tok/s")
Continues meeting.py (part 7 of 9), same file.
python
with urllib.request.urlopen(HOST + "/api/ps") as f:
window = next(m["context_length"] for m in json.load(f)["models"]
if m["name"] == CHAT)
print(f"context window on this server: {window:,} tokens")
meetings, busiest = 1_00_000, 0.15
classes = [(6_000, 0.95), (24_000, 0.05)] # words, share of meetings
out_one, notes_out, reduce_out = 700, 400, 100# tokens, assumed
chunk_words = 6_000
avg = 0for w, share in classes:
tokens_in = w * tok_per_word + fixed
if tokens_in + out_one <= window:
how = "one call"
secs = tokens_in / prefill + out_one / decode
else:
n = -(-w // chunk_words)
tokens_in = w * tok_per_word + n * fixed
how = f"{n} chunks and a merge"
secs = (tokens_in / prefill
+ (n * notes_out + reduce_out) / decode)
avg += share * secs
print(f"{w:>6,} words: {tokens_in:>6,.0f} tokens in, {how}, "
f"{secs:.0f} model seconds")
print(f"average: {avg:.0f} model seconds a meeting")
Continues meeting.py (part 8 of 9), same file.
python
day = meetings * avg
print(f"a day: {day:,.0f} model seconds = {day / 86_400:.0f} "
f"streams busy all day")
hour = meetings * busiest * avg
print(f"busiest hour: {meetings * busiest:,.0f} meetings")
print(f" streams needed: {hour / 3600:.0f} within the hour, "
f"{hour / (3 * 3600):.0f} within three")
# 4. The code checks on answers a model might give (made up).
made_up = [
{"task": "Update the logo", "owner": "Rohit", "due": None,
"evidence": "Arjun: Yes, I will fix the timeout"},
{"task": "Share the budget", "owner": "Kavya", "due": "Friday",
"evidence": "Kavya: I will share the budget sheet"},
]
for a, why in check(made_up, TRANSCRIPT, ATTENDEES)[1]:
print(f"flagged: {a['task']}: {'; '.join(why)}")
Continues meeting.py (part 9 of 9), same file.
text
transcript: 212 words, 4 attendees
one call in 402 out 405 prefill 119 decode 10526 (ms)
summary: The team discussed technical bugs on the leave page,
including session timeouts and date picker issues, and the status
of the approval screen design. They also addressed the manager
dashboard performance and the e-signature licensing costs. The
team agreed to proceed with the release on the 20th without the
dashboard fix.
action: Arjun | Fix the session timeout and push it to staging | due
Thursday
action: Arjun | Open a ticket for the date picker bug | due today
action: Kavya | Send the design file to Imran | due Friday
action: Imran | Book five phones from the device lab | due Wednesday
action: Meera | Ask Finance about e-signature license costs and
inform the team | due Monday
decisions: 2
chunk 1/3 in 210 out 193 prefill 102 decode 5229 (ms)
chunk 2/3 in 202 out 205 prefill 1581 decode 5432 (ms)
chunk 3/3 in 186 out 155 prefill 83 decode 4845 (ms)
reduce in 153 out 72 prefill 99 decode 2444 (ms)
final summary: The team addressed bugs on the leave page and
identified a performance issue with the manager dashboard. Kavya
and Imran are coordinating on design finalization and securing
test devices, while Meera will handle finance inquiries regarding
e-signature costs. The team confirmed the release date for the
twentieth, excluding the dark mode fix.
chunked actions: 5 | calls: 4
A real run. The times are on this machine, share its GPU and vary.
text
measured: 101 fixed tokens a call, 1.39 tokens a word
prefill 2,069 tok/s, decode 36.9 tok/s
context window on this server: 32,768 tokens
6,000 words: 8,450 tokens in, one call, 23 model seconds
24,000 words: 33,800 tokens in, 4 chunks and a merge, 62 model seconds
average: 25 model seconds a meeting
a day: 2,501,821 model seconds = 29 streams busy all day
busiest hour: 15,000 meetings
streams needed: 104 within the hour, 35 within three
flagged: Update the logo: owner is not an attendee
flagged: Share the budget: evidence is not in the transcript
The rest of the run.
Reading the numbers
The transcript is 212 words with four attendees. In one call the model found five action items with the right owners and due dates, and left out the two things nobody took on, the slow dashboard and the dark mode. In three chunks plus a merge it found the same five. The single call read 402 tokens and wrote 405. The chunks read 598 and wrote 553, and the merge wrote 72 more, so chunking costs extra writing. The last two lines are made-up answers, a task whose owner was not at the meeting and a task whose quoted words are not in the transcript. The check flags both.
The run measured 101 tokens of instructions on every call, 1.39 tokens a word, reading at 2,069 tokens a second and writing at 36.9. The writing speed swings on this shared server: other runs of the script gave between 30 and 55. At those rates a 6,000-word meeting is 8,450 tokens, which fits the 32,768-token window with room for the reply, so one call takes about 23 model seconds: 4 reading and 19 writing. A 24,000-word workshop does not fit, so it goes in four chunks and a merge and takes 62 seconds. The average is 25 model seconds a meeting, about 25 lakh a day, which keeps 29 streams busy all day. The busiest hour needs 104 streams if every meeting is served within the hour, and 35 if within three.
The number that drives the design is model time per meeting, about 25 seconds, because it fixes how many model streams the company must run, and most of it is spent writing, not reading.
Model answer: from transcript to notes
Requirements. Functional: accept a transcript with its attendees; produce a summary, the decisions and the action items, each with an owner and a due date; post them to the attendees. Non-functional: notes within 10 minutes; every owner is an attendee and every item carries the words that justify it; transcripts stay inside the network; a repeated delivery of the same meeting produces one set of notes.
Data model. A meeting row holds the meeting id, the attendees, the date and a state: received, summarising, done or review. The transcript is a blob in the blob store, keyed by the meeting id. A notes row holds the summary, the decisions and the items, and each item has an owner, a due date, its evidence and a status, posted or needs review.
Design, in order. The meeting platform calls the API with the transcript and an idempotency key made from the meeting id, so a retried call returns the first answer and starts no second job. The API stores the transcript and puts a job on a queue with a deadline. A worker counts the tokens. A transcript that fits the window with room for the reply goes in one call. A longer one is cut at speaker turns into chunks of about 6,000 words, each chunk yields notes and candidate items, and a last call writes one summary from the notes. The items are merged in code, never by the model.
Every item then passes the checks in the script: the owner must be an attendee, and the quoted words must occur in the transcript. A relative date such as Thursday is turned into a calendar date in code, from the meeting date. Items that fail go to review and are not posted. The result is stored and sent to the attendees through a notification service like the one in the second prompt.
In front of the model servers sit a bounded queue, a deadline per job and a token bucket per company counted in tokens, as in the rate limiter chapter and the ai building blocks chapter, so that one company's workshop day cannot use the whole fleet.
Model answer: deep dives and trade-offs
Deep dive 1: long meetings. A workshop does not fit the window, so it is cut at speaker turns, and the last few turns of each chunk are repeated at the start of the next, so that a sentence such as "I will do that" keeps its subject. Items from all chunks are merged in code and a repeat is dropped by its evidence text. The run shows the cost: chunking wrote 625 tokens against 405 for one call. So the design chunks only when a transcript does not fit.
Deep dive 2: trusting the output. Four guards sit between the model and a person. The reply must parse against a schema. The owner must be an attendee. The evidence must occur in the transcript. An item with no owner is shown as unassigned for someone to claim, never given to a guess. A transcript is also untrusted text: someone can say "ignore your instructions" aloud. The model has no tools and posts nothing; only code posts. To know the notes are good, keep a set of transcripts with hand-marked items, count the items found and the false ones, and run it on every change of prompt or model, as the ai building blocks chapter describes.
Trade-offs. Serving within the hour needs 104 streams and within three hours 35, so a looser deadline is the cheapest saving, and the 10-minute promise costs about three times as much. A strict evidence check rejects a valid item whose quote was paraphrased, so some go to review that did not need to. A smaller model is faster and misses more items.
Failure. If the model server is down, jobs wait in the queue and retry with backoff and jitter. Past the deadline the service posts a short message that the notes are late, and does not stay silent. A chunk that fails is retried alone.
Score yourself
Line
A 4 on this prompt includes
Requirements
No invented owners or tasks as a hard requirement, notes within 10 minutes, and recording and editing out of scope
Estimates
About 25 model seconds a meeting, and 104 streams in the busiest hour against 35 with a looser deadline
Design
API with an idempotency key, queue, one call or chunks, checks in code, and posting
Deep dive
Chunking with its extra cost, and the guards on the model's output
Trade-offs
Deadline against streams, chunk size, strict checks against review load, and model size
Communication
Names model time as the driving number early and returns to it
Why is model time per meeting the driving number, and not the size of the transcripts?
It fixes the streams: 15,000 meetings in the busiest hour at about 25 seconds is 104 streams if all are served within the hour.
Reading is fast, about 2,069 tokens a second, and writing is slow, about 37, so the time follows the notes written.
The model names an owner who was not at the meeting. What happens?
The check finds the owner is not in the attendee list, flags the item and sends it to review.
Nothing is posted under that name, and the model has no way to post on its own.
Why not cut every transcript into chunks?
Each chunk writes its own notes, so the run wrote 625 tokens against 405 for one call, and writing is the slow part.
One call is used when the transcript fits the window with room for the reply.