Learn system design one part at a time
New here? Follow the route: 34 lessons in order, each about ten minutes. Every lesson builds its picture step by step, and the numbers on it are measured as it runs.
Start the routeWho is sending the traffic?241 lessons to read, 34 of them on the route · 5 coming soon
The route 34 lessons in order, and 5 challenges
Stage 0 · The prototype
- Step 1: Who is sending the traffic?Who is really sending the requests: one person, a crowd, or a script.
- Step 2: When one server is not enoughWhat happens when one server cannot keep up, and the first fix.
- Step 3: Single points of failureFind the one part whose crash takes everything down.
- Step 4: Stage 0: the prototype on one machineThe shop on one machine: what a single crash costs, and the dangers you cannot see.
- Keep the shop open when the app’s machine stopsOne app machine stops. Keep orders flowing for under $350 a month.
Stage 1 · Launch
- Step 5: Capacity estimationTurn “a million people” into servers, before the launch, not during it.
- Step 6: Cache-asideAnswer the same question once, not a thousand times.
- Step 7: CDN edge cachingServe pictures and pages from near the reader.
- Step 8: System cost estimationPut a monthly price on a design, and cut the biggest line.
- Step 9: Do the slow part laterSay yes at once, and do the slow part later.
- Step 10: Retry with backoffTry again without making a bad day worse.
- Step 11: Stage 1: launch, and the first paymentsThe first payments: why a retry can charge a customer twice, and the key that stops it.
- Charge every customer exactly onceLost replies and retries charge people twice. Make it once.
Stage 2 · First paying customers
Stage 3 · Production
- Step 13: Slow replies and time budgetsWhy the slowest replies matter most, and how to share out the time.
- Step 14: Stage 3: productionA written promise for speed, and the cache that keeps it when the data outgrows memory.
- Hold 900 a second when the table outgrows memoryReads now go to disk. Hold 900 a second for under $500 a month.
Stage 4 · Black Friday
- Step 15: Read replicasCopies of the database that take the reads.
- Step 16: Database shardingWhen even copies are not enough: split the data.
- Step 17: Rate limitingStop one caller from taking everyone’s share.
- Step 18: Stage 4: Black FridayTen times the traffic on sale day: what breaks first, and what fixes it.
- Hold Black Friday under $1,800 a month15,000 a second. Under 1% failing, p95 under 300 ms, under $1,800.
Stage 5 · Big data
Stage 6 · Many zones
Stage 7 · Many regions
Security essentials
- Step 23: Authentication and authorizationWho is calling, and what they may do: sessions, tokens, checks.
- Step 24: OAuth 2.0 and OpenID ConnectSign in with another account, and let apps act for a user safely.
- Step 25: Cryptography fundamentalsEncode, hash, encrypt, MAC, sign: which one does what.
- Step 26: Encryption in transit and at restLock data on the network and on disk, and keep the keys apart.
Interview practice
- Step 27: Ask before you drawAsk who, how many and how fresh before drawing anything.
- Step 28: Numbers to knowThe handful of figures that make every estimate quick.
- Step 29: Design a URL shortenerThe first interview problem, worked end to end.
- Step 30: Design a news feedBuild each feed ahead of time, except for the famous accounts.
- Step 31: Design a chat appMessages that arrive at once, in order, and are never lost.
- Step 32: Design ticket bookingA rush for a few seats: a waiting room, and never selling one twice.
- Step 33: Design a rate limiterDesign the limiter itself: where it counts, and how it fails.
- Step 34: Security in design interviewsRaise the security points an interviewer listens for, at the right time.
Branch: Security in depth 7 lessons in order, off the route
Take it whenever you want to go deeper. Its last lesson leads back to the route.
- Step 1: Password storage and credential stuffingStore passwords so a stolen table is useless, and slow the guessers.
- Step 2: MFA and passkeysA second proof, and sign-ins a phishing page cannot steal.
- Step 3: Web security basicsThe browser’s own guards: cookies, CORS, CSRF, XSS and CSP.
- Step 4: The OWASP Top 10The ten ways web apps most often break, each played and fixed.
- Step 5: API securityAPIs leak by object, field and function: the checks that stop it.
- Step 6: Secrets managementKeep passwords and keys out of code, and make them expire.
- Step 7: Threat modellingAsk what could go wrong, box by box, before it is built.
From prototype to millions 8 lessons
- Stage 0: the prototype on one machineA founder puts the whole shop on one rented server: the app and its database side by side. It is fast and cheap, and when the machine stops, everything stops. The dangers that really bite at this size are quieter ones.
- Stage 1: launch, and the first paymentsThe shop launches and strangers pay by card. A card provider that is sometimes slow, plus a sensible retry, quietly charges some customers twice. One key per order fixes it. A CDN takes the photos off the app, and two people learn to ship without breaking things.
- Stage 2: first paying customersPeople now pay, and every order sends a receipt email. A slow email provider should never be able to stop a customer from paying.
- Stage 3: productionThe shop is now something people rely on. Write down what “working” means, notice when it stops, and remove the parts that can take it down.
- Stage 4: Black FridayTen times the traffic, planned for. Break the shop on purpose three weeks early, one wall at a time: the API, the database, the bots.
- Stage 5: big dataThe writes outgrow the biggest machine. Split the data by customer, and grow from four shards to five without moving most of it.
- Stage 6: many zonesA whole building goes dark. Spread the shop over two zones, fail over to a standby, and decide which data may never be lost.
- Stage 7: many regionsShoppers on the other side of the world, and a whole region going dark. Serve reads nearby, keep one truth, and fail over to another continent.
System design fundamentals 6 lessons
- Single points of failureTwo copies of a server survive one crash. One database, or one front door, takes everything down with it. Find each one, then count what removing it buys.
- Capacity estimationBefore launch day, work out how many requests will arrive at the busiest moment and how many servers that needs. Then run it and see whether the estimate holds.
- System cost estimationTurn a design into a monthly bill from named, dated prices, find the biggest line, and cut that one first, without breaking what the shoppers feel.
- Slow replies and time budgetsMost shoppers get a quick reply; a few unlucky ones wait much longer. Measure the slow ones, not the average, and agree up front how much time each part may spend.
- Ask before you draw“Build a fast order page” can mean one small server or a load balancer, four servers and a cache. Ask who, how many, how fresh and what can fail, turn the answers into numbers, and write them down.
- Numbers to knowA handful of rough numbers lets you size a design in your head: how slow each hop is, how much one machine can do, what each extra nine of uptime buys, and how big things are.
Coming soon: 5 lessons still being reviewed
- API design
- Bottleneck analysis
- Functional and quality requirements
- High-level architecture
- System design trade-offs
Case studies 39 lessons
- Design a URL shortenerThe classic first interview question, worked end to end: agree the requirements, estimate, two calls, one table, then fix one wall at a time.
- Design a news feedThe newest posts from everyone you follow: build each feed when it is opened, or ahead of time, and the famous accounts that break the second way.
- Design a chat appMessages that arrive at once, in order, and are never lost: open connections, a store split by conversation, delivery through a queue.
- Design ticket bookingA rush of fans for a few seats: a waiting room that serves them in order, and a hold that never sells one seat twice.
- Design a rate limiterShare an API fairly between thousands of customers: where to count, how to count, where the count lives, and what to do when the limiter itself breaks.
- Design an ad click aggregatorCount a billion clicks a day per ad per minute: redirect first, log every click, count in memory and write once a minute, then make the bill exact overnight.
- Design ads ranking: the shop’s sponsored listingsSellers pay to put their products at the top of the shop’s search results. Pick the ads that earn the most per search, without showing ones nobody clicks: rank by bid times the chance of a click, keep that chance honest, wait for late purchases, and make each budget last the day.
- Design AirbnbHomes to search and nights to book: a quadtree search with answers saved per map cell, a row per night guarded by a version check, and why low contention makes optimistic concurrency the right guard.
- Design a ChatGPT-style assistantThe interviewer says: “Design ChatGPT.” Build the shop’s chat assistant twice over: how its model is trained (pretraining, instruction tuning, preference tuning) and how one message is served (safety checks, history in a context window, batching, streaming, limits per user), then how you know it is good.
- Design a distributed cacheA shared memory in front of the database: size it by memory and by lookups, split keys over nodes, keep it right, and survive losing a node.
- Design a distributed message queueKafka from the inside: a log read in order, partitions shared by a consumer group, copies on other brokers, and what acks=1 and acks=all promise when the leader dies.
- Design DoorDashFood delivery at the dinner peak: orders accepted at once, a dispatcher behind a queue that finds nearby dashers in memory, more dispatchers for the rush, and batching for better trips.
- Design DropboxThe same files on every device: a file list in a database, bytes as blocks named by their hash, only changed blocks sent, and devices told of changes at once.
- Design a ranked social feedThe photo-sharing app from Design a news feed now ranks its feed by interest and mixes in posts from people you do not follow. Predict several actions per post, weigh them into one score with a negative weight for hides, give new posts a fair start, and learn from logs that lie about the top slot.
- Design a flash saleAmazon-style checkout for 10,000 consoles and two million buyers: the read-then-write race that oversells, a lock that makes one long line, and one short statement over split stock rows.
- Design Google DocsMany people typing in one document: small edits over open connections, a log of edits with snapshots instead of a write per keystroke, and one order everyone agrees on.
- Design Google MapsA map of the world and the fastest way through it: tiles by fixed address behind a CDN, a road graph in memory, and shortcuts computed ahead of time so routes take milliseconds.
- Design InstagramPhotos for 500 million people: files in object storage, uploads accepted at once and resized behind a queue, and a CDN that sends photos from near the viewer.
- Design a job schedulerRun each job at its time, once: a table indexed by the next time, claim and queue, spread the midnight burst, and keys that make retries harmless.
- Design a key-value storeDynamo and Cassandra from the inside: keys spread by a hash, a ring so adding a node moves only a ninth, three copies with quorum reads and writes, and what reading one copy gives up.
- Design a real-time leaderboardA game’s top 100 and “where am I” for ten million players: a database that drowns on finale night, a Redis sorted set that keeps the ranking in memory, boards as keys, and top K by counting.
- Design live commentsComments on a live video for 2 million viewers: open connections with room for everyone, a log every server reads, and bundles that make 800 million pushes a second fit.
- Design a metrics and monitoring systemTen thousand servers reporting every 5 seconds: dashboards that fail during an incident until rollups make each chart read 30 times fewer points, and a log that keeps every point while the store is down.
- Design a notification systemTell people things on time and once, through providers you do not control: accept and queue, pace to their limits, separate channels, and keep repeats harmless.
- Design an online auctioneBay-style bidding on one hot item: version checks that turn into a retry storm in the last minute, one atomic statement that still makes a line, and a log with one in-memory sequencer per auction.
- Design a payment systemCharging cards for shops exactly once: a hot balance row that makes a line on Black Friday, an append-only double-entry ledger, idempotency keys that make retries safe, and nightly reconciliation.
- Design a RAG assistant over company documentsThe interviewer says: “Design a ChatPDF for our company.” Staff ask questions and get answers from the shop’s own documents, with sources. The hard parts: the parse-chunk-index pipeline, never showing anyone a document they cannot open, keeping answers fresh when documents change, and evaluating each part with the RAG triad.
- Design a recommendation system: “Recommended for you”The shop’s home page shows each shopper a row of products picked for them. Built the way large shops and feeds build it: cheap candidate sources, a light ranker, a heavy ranker that predicts several actions, rules over the row, and a log that turns every row shown into training data.
- Design S3 (object storage)Files that are never lost: an index of names, bytes spread over machines by hash, three copies in three zones with a write done at two, and erasure coding for cold data.
- Design a stock exchangeMatching orders fairly at the opening bell: an order book per stock that a lock limits to one line, a sequenced log with an in-memory matching engine per stock, and risk checks before the line.
- Design TinderPeople nearby and a flood of swipes: decks from a quadtree location index, swipes sharded by person, matches checked on one shard, and decks built ahead of time.
- Design TwitterThe home timeline for 200 million people: copy each tweet to its followers ahead of time, find the famous accounts that jam it, and fetch their tweets when the timeline is read.
- Design typeaheadSuggestions under a search box, a million letters a second: prepare the top five per prefix, cache it, answer at the edge, rebuild every hour.
- Design UberFinding the nearest drivers for millions of riders: a location index, a quadtree that keeps downtown searches cheap, live locations in memory, and one driver locked per ride.
- Design a unique ID generatorIDs for every post and order, 20,000 a second: one database counter that cannot keep up, odd and even ticket servers, and Snowflake IDs made inside each service from time, machine and sequence.
- Design a web crawlerFetch a billion pages a month without being rude, wasteful or stuck: a frontier, a queue, fetchers that wait on many pages at once, and rules for repeats and traps.
- Design WhatsAppOne-to-one messages for 2 billion people: a log between chat servers, an inbox for people who are offline, and routing so each message is read by the one server that holds its recipient.
- Design YelpPlaces near me for 100 million people: a location index of geohash cells, answers saved per cell because places barely change, and ranking refreshed in the background.
- Design YouTubeVideos for a billion people: uploads made behind a queue, each video cut into parts many machines make at once, pieces at five sizes, and a CDN that sends them from near the viewer.
Networking & traffic 14 lessons
- CDN edge cachingAn edge cache near the viewer answers repeat requests itself, so the origin sees a trickle instead of the whole crowd.
- Rate limitingA token bucket per caller admits bursts up to a limit and answers 429 beyond it, so one heavy caller cannot sink everyone else.
- API gatewayOne public API address checks the caller’s token, picks a route and forwards to a private service.
- Consistent hashingKeys and servers share one ring; a key belongs to the next server clockwise, so adding a server moves only one slice of keys.
- DNS resolutionA device asks one recursive resolver for a name; on a miss the resolver follows referrals from the root to the authoritative server.
- gRPCA typed method call across the network: a .proto contract, generated code, Protocol Buffers on an HTTP/2 stream.
- The life of an HTTP requestFollow an order-page request from the DNS lookup through the connection to the HTTP/2 request and its JSON reply.
- Layer 4 load balancingA TCP listener pins each connection to one healthy target; how fast it notices a dead one decides how many requests fail.
- Layer 7 load balancingThe balancer decrypts each request and routes it by host and path, so separate services sit behind one address and fail separately.
- Reverse proxyOne public address in front of private services: the proxy forwards each request and, with more than one backend, spreads the load.
- Service discoveryServices register their healthy instances; callers either look one up themselves or send to a proxy that does.
- TCP three-way handshakeTwo peers exchange SYN, SYN-ACK and ACK so each knows the other’s starting sequence number before any data flows.
- TLS terminationA terminator proves the site’s identity with its certificate, decrypts the request and forwards it to the application.
- WebSocketsAn HTTP request upgrades into a long-lived, two-way channel where either side can send frames at any time.
Caching & performance 11 lessons
- Cache-asideThe application asks Redis first, reads PostgreSQL on a miss and fills the cache, and the database stops drowning.
- Bloom filtersA row of bits and a few hashes answer "is this key in the set?" with "definitely not" or "maybe", so most lookups for missing keys skip the disk. No false negatives; the false-positive rate is set by bits per key and climbs as the filter fills.
- Cache eviction policiesA full cache must drop a key or refuse a new one; the run measures LRU, LFU, random and noeviction on the same traffic.
- Cache invalidationDelete the cached key after the database commits, deliver that delete reliably, and fence the race that refills an old value.
- Cache stampedeWhen a popular key expires, many simultaneous misses can each query the database; a lease lets one loader refill it for everyone.
- Distributed cacheStateless API replicas share one cache whose keys are spread across nodes, so losing a node costs only its share of the keys.
- Hot keysOne very popular key overloads the single cache shard that owns it; local copies and read replicas spread the heat.
- Read-through cachingThe application asks one interface for a value; on a miss the cache’s own loader reads the database and fills it.
- TTL expirationA time to live bounds how stale a cached value can get; the numbers show what each shorter TTL costs the database.
- Write-behind cachingThe cache accepts a write first and carries it to the database later, trading a fast answer for a window of lag.
- Write-through cachingA write reaches the database and the cache before it is reported done, with a durable intent to repair the cache when it fails.
Databases & consistency 26 lessons
- Read replicasSend changes to the primary and reads to read-only copies. The primary gets its room back; the price is that some reads can be a moment old.
- Database shardingSplit the data across separate databases by a shard key, so each one holds and serves a slice. One very busy key, or a question without the key, undoes the split.
- Backups and disaster recoveryA replica copies mistakes too. Night copies plus the archived log bring data back to any second; RPO says how much you can lose, RTO how long you are down, and only a tested restore proves either.
- ACID transactionsA transfer debits one account and credits another inside one transaction: both changes commit together, or a failed check rolls both back.
- Asynchronous replicationThe primary commits and answers without waiting for its standby. Writes are fast; a standby can be behind, and a failover can lose the newest commits.
- CAP theoremWhen the link between regions breaks, a booking system must choose: refuse some requests to keep one answer, or accept them and sort out conflicts later.
- Connection poolingOpening a database connection costs round trips and a process. Pools reuse a few; Little's law and the core count size them; PgBouncer shares them across many servers, at the price of session state.
- Consistent hashing for shardsA partition key and every shard host’s tokens sit on one ring; the key belongs to the next token clockwise, so a new host takes over only one slice.
- Data modeling and schema designKeys, references and constraints come from the rules the data must keep; indexes come from the questions it must answer; changes roll out so old and new code can overlap.
- Eventual consistencyReplicas may disagree for a while after a write. Reads at ONE can see the old value; hints and repair make every copy converge.
- Indexing and query plansThe planner uses table statistics to choose between an index and a full scan; a composite index in the query’s shape finds a few rows without reading them all.
- Isolation levelsTwo overlapping transactions each read a safe snapshot and each make a safe change; under Repeatable Read both commit and break the rule, Serializable aborts one.
- Merkle trees and anti-entropy repairReplicas drift apart when a node misses writes. Merkle trees find the few ranges that differ with a handful of hash comparisons; repair streams only those, and must run more often than gc_grace_seconds or deletes come undone.
- Multi-region databasesOne region holds the writable primary and streams its log to a standby far away; a nearby read there is fast but can be one version behind.
- Optimistic concurrencyEach save names the version it was based on; the update only matches that version, so a stale save changes nothing and the user is asked to reload.
- Paxos and RaftBasic Paxos chooses one value with prepare/promise and accept/accepted; Raft elects a leader per term and commits an ordered log once a majority stores each entry.
- Pessimistic lockingA transaction locks the row before it checks it, so a competing writer waits; locking rows in opposite orders can deadlock, and the database breaks the cycle.
- Primary-replica replicationThe primary commits, streams its write-ahead log to a standby, and the standby replays it; until replay, a read there can be one version behind.
- Quorum reads and writesWith three copies, write to two and read from two: every read overlaps the latest write. The levels you choose trade staleness against availability.
- Relational vs NoSQL databasesThe same checkout on PostgreSQL, MongoDB and DynamoDB: all three can keep stock and orders correct, each shapes the data and the queries differently.
- Search and the inverted indexLIKE '%…%' scans every row and cannot rank. An inverted index maps analysed words to the products that contain them, BM25 ranks the matches, and change data capture keeps the index a moment behind the database.
- Strong consistencyTwo shoppers race for the last voucher. A linearizable compare-and-set lets exactly one win, and any later read sees the winner.
- Synchronous replicationThe primary waits until a standby confirms it has the commit on disk. Each write pays a round trip; a failover loses nothing that was acknowledged.
- Two-phase commitOne transfer, two databases: commit on one and fail on the other and money vanishes. Two-phase commit makes both agree (prepare, vote, decide, finish), at the price of round trips, held locks, and blocking when the coordinator dies.
- Vector clocks and conflicting writesWhen two replicas accept writes during a split, last write wins silently drops one, and clock skew can make it drop the newer one. Vector clocks detect concurrent writes so they can be merged; Lamport clocks, hybrid logical clocks and CRDTs fill in the rest.
- Write-ahead loggingA change is written to the log and flushed before success is reported; table pages are written later, and after a crash the log replays what they missed.
Messaging & reliability 18 lessons
- Retry with backoffRetry short-lived failures a few times, waiting longer between tries with a little randomness; stop on permanent errors and when time runs out.
- Bulkhead isolationGive each dependency its own small pool of workers, so one saturated feature cannot take capacity from another.
- Circuit breakerAfter enough failures the caller stops calling a broken dependency for a while and fails fast, so the rest of the service stays up.
- Consumer lagLag is the distance between a partition’s log end and a group’s committed position, counted in records, not seconds.
- Dead-letter queuesAfter a few failed deliveries a message is moved aside, so a message that can never succeed stops circling and blocking work.
- Delivery semanticsWhen you commit the offset decides what a crash costs: a lost payment, or a replay that a unique event id turns into a no-op.
- Distributed tracingA trace id travels in a header across every service; each hop records a span with its parent, and the spans are exported and joined into one waterfall.
- Event sourcing and CQRSA row that holds only the current balance cannot say why it is 40 or what it was last Tuesday. Event sourcing stores every change as an append-only event and folds them into state; CQRS feeds separate read models from those events.
- Failure mode analysisWalk one failure through detection, impact, containment and recovery before it happens for real, and measure the recovery against its target.
- Idempotency keysThe client names each intended payment with a key; the server stores the outcome under it and replays it for any retry.
- Kafka consumer groupsMembers of one group split a topic’s partitions between them; separate groups each read everything, with their own progress.
- Kafka topics and partitionsA keyed record goes to one partition’s leader, is appended at the next offset, and is copied by follower brokers.
- Message queueHand slow work to a queue: the caller gets an answer at once, consumers work through the backlog, and a crashed consumer’s message comes back.
- Observability fundamentalsMetrics say how often and how badly, traces say where, logs say why; one shared id connects all three to the same failing request.
- Outbox patternWrite the order and its event in one database transaction; a relay publishes the event later, possibly twice, and consumers deduplicate.
- Publish-subscribeOne event, published once, reaches every subscriber through its own queue, so each one works and fails on its own.
- Saga patternA booking spans services that each commit locally; when a later step fails, earlier ones are undone by compensating actions.
- Timeout budgetsOne deadline travels with the request; every hop gets only what is left, so the whole call finishes or gives up on time.
Infrastructure & delivery 15 lessons
- Artifact registryCI pushes an image to a private registry; policy checks the exact digest, the release pins it, and nodes pull and verify it.
- Blue-green deploymentRun the new version beside the old at full size, test it privately, switch all traffic at once, and switch back if it goes wrong.
- Canary deploymentSend a small share of real traffic to the new version, compare its health with the old one, and promote or abort.
- CI build and testEvery commit is checked out on a clean runner, built and tested; only commits that pass the required checks may merge and produce an artifact.
- Containers and imagesBuild an image once from ordered layers, name it by digest, and run identical containers from it anywhere; keep data outside the container.
- Deployments and rolloutsChanging a Deployment’s template rolls out new pods a few at a time, gated by readiness, while old ones are scaled down.
- Horizontal autoscalingThe autoscaler compares measured CPU with a target and changes the replica count, within limits, on a feedback loop.
- Infrastructure as codeDescribe infrastructure in reviewed files; a tool compares them with what exists, shows the plan, and applies exactly what was approved.
- Ingress routingAn Ingress controller terminates TLS for a hostname and routes paths to Services inside the cluster, from rules stored as API objects.
- Kubernetes podsA Deployment keeps a number of pod replicas; probes decide when a pod gets traffic or is restarted, and a lost pod is replaced.
- Kubernetes schedulingThe scheduler filters out machines where a pod cannot fit, scores the rest and binds it; with no room the pod waits Pending.
- Kubernetes ServicesA Service is a stable name and virtual IP in front of whichever pods are ready; the endpoint list follows pod readiness.
- Node failure recoveryWhen a machine stops reporting, Kubernetes waits, evicts its pods and recreates them on healthy machines, if there are any.
- Readiness and liveness probesStartup, readiness and liveness probes answer different questions: has it started, may it take traffic, should it be restarted.
- RollbackRestore the last good version quickly, then deal separately with the data and side effects the bad one left behind.
Data engineering 21 lessons
- Backfills and idempotencyA backfill re-runs past days, say after a bug fix. Measured: appending counts each day twice, replacing the day’s partition fixes it, and a task that takes its date from the clock puts every re-run into one day.
- Batch processingA batch job works through a closed pile of data, such as yesterday’s orders, in one run. Split it into partitions so workers run side by side, retry only the one that fails, and publish every output at once so nobody sees half a day.
- Broadcast or shuffle?Spark joins a small table by copying it to every executor, and a big one by shuffling both sides. Measured: the default threshold that misses a small table, and the broadcast that runs out of memory.
- Catch-up runsAfter the scheduler has been off, catch-up creates a run for every day it missed. Measured: the gap without it, and why running them all at once is slower than two at a time.
- Change data captureCopy every insert, update and delete out of a live database as it happens. Measured on one day of orders: polling never sees deletes, reading the log does, and a stalled log reader can stop the shop.
- Data lakeKeep the raw orders as plain files in cheap object storage, then make them a table with a catalog. See what a query reads, and what goes wrong with no catalog or with thousands of tiny files.
- Data partitioningSplit one huge table into one partition per day, and a query for one day reads one partition. See the planner skip the rest, and the filters that quietly stop it from skipping anything.
- Data quality checksA pipeline can succeed and still load bad rows. Test the data before publishing it: no missing keys, no repeats, only known values, enough rows, fresh enough. Then decide what a failure does: warn, drop, quarantine or fail.
- Data warehouseBig questions over history do not belong on the database that takes the orders. Follow one night’s orders into a warehouse: staged, checked, modelled as a star schema, and asked “revenue by date”.
- ETL vs ELTClean the data before storing it (ETL), or store it raw and clean it inside the warehouse (ELT). Measured over two weeks: what each one can redo when a bug is found.
- Event-time windowsCount each order in the window of the minute it happened, not the minute it reached you. Late phones make the difference, and keeping windows open for them has a cost.
- Fresh, complete, accurateA pipeline can be up, fast and wrong. Promise three things instead of uptime: how fresh, how complete and how accurate the data is, and check them against the source.
- What breaks if it is late?Before choosing streaming or batch, ask who reads the data and what breaks if it is an hour or a day old. The answer picks the design, and the bill.
- LakehousePut an open table format (Apache Iceberg, Delta Lake) over the lake’s files: a write is all or nothing, old versions stay readable, columns can be added without rewriting files, and bronze, silver and gold are real tables.
- Late-arriving eventsSome orders reach the processor after their window has closed. Drop them, correct the window, or keep them aside for a fix-up: each choice is measured on the same day.
- Materialized viewsA dashboard query that adds up every order on each load is slow. A materialized view stores the answer, so reads are fast, but it goes stale with every new order until it is refreshed. See full versus incremental refresh, and why PostgreSQL’s CONCURRENTLY keeps readers from waiting.
- Skew and saltingWhen one key holds a big share of the rows, one task does most of the work while the cluster waits. Measured: why more executors do not help, and two ways of salting the key.
- Spark in one pictureA driver plans the job and splits it into stages at every shuffle; executors run one task per piece of data. Measured: what more executors buy, and why a join costs more than a total.
- Stream processingA stream processor keeps running totals and saves them in checkpoints. When it crashes it replays from the last one, and whether that counts sales twice depends on the table it writes to.
- WatermarksA watermark is the processor’s guess of how far event time has got. It closes windows. The slowest partition sets it, so one quiet partition can freeze the dashboard.
- Workflow orchestrationAn orchestrator such as Airflow runs a pipeline’s steps in order, each one only after the step before has succeeded, and retries the ones that fail. Measured over two weeks against cron’s fixed times.
AI & data systems 45 lessons
- A/B tests that don’t lieAn A/B test shows a new ranker to a random half of the shoppers and compares. It is the last word on whether a change helps, and it is easy to fool: peeking, a broken split, novelty and a win paid for elsewhere. Run on the shop’s seeded shoppers, with interleaving as the fast variant.
- Evaluating an agent: once is not enoughAn agent can pass a test today and fail the same test tomorrow. See how to test one properly: real tasks in a safe copy of the shop, outcomes checked by code, every task run several times, and a model judge only where code cannot check.
- Agent handoffs: passing a customer to a specialistA shop’s triage agent finds out what a customer needs, then hands the conversation to a refunds specialist. See what a handoff really is (a tool call the model makes), how it differs from calling an agent as a tool, what has to travel with it, and how handoffs go wrong.
- The agent harness: everything around the modelThe model only reads text and writes text. The harness is the program around it: it runs the loop, runs the tools, decides what goes into the context window, and checks every action before it happens.
- Agent memory: what an agent remembers, and whereA language model forgets everything between calls. An agent seems to remember because the app keeps the conversation in its context window, squeezes it when it fills, and writes lasting facts to a store it can search days later. See both kinds of memory, and how they go wrong.
- Agent observability: tracing every model and tool callOne customer message can set off many model calls, tool calls and a handoff. A trace records them all as nested spans on one timeline. See how to find the slow step, a retry loop and the cost of a run, and how to keep customers’ personal data out of your traces.
- MCP and A2A: tools and other agentsMCP connects an agent to tools; A2A connects it to other agents. See both on one shop assistant: an MCP tool call, then a task handed to a courier company’s agent.
- Agent sandboxes and computer useAn agent that writes and runs code, or clicks around a screen, is running instructions nobody has read. Give it a box it cannot escape: a fresh sandbox per job with no secrets, an allow-listed network and hard limits, thrown away after; and for screens, a look-act-look loop with a person before any money button and a step limit.
- Agent state and checkpointsAn agent’s task can take minutes or wait days for a person. Save each step as it happens, pause safely before side effects, and resume after a crash without doing anything twice.
- Agent tool callingA language model cannot do anything by itself; it can only ask. See how an app turns those asks into safe tool calls, and why spending money needs a person’s yes.
- Agentic RAG: retrieve, check, try againPlain RAG searches once and hopes. Agentic RAG lets an agent decide whether to search, split a question that needs several facts into steps, check that each search really answered, rewrite and retry, and say “not found” instead of guessing.
- AI governance and compliance: prove it, erase it, stop itAn AI assistant must answer three questions: why did it say that, can you delete everything about me, and what stops a document from giving it orders? Audit records, erasure by lineage and a policy check outside the model answer them, mapped to the rules that ask.
- Approximate nearest neighbour searchFollow one question down an HNSW index, level by level, and see the setting that trades accuracy for speed. Then measure what it missed.
- Calibration: does a 20% chance mean one in five?A model can put products in the right order and still be wrong about how likely each one is. Calibration checks the size of the chances against what really happened, bin by bin, in a reliability diagram. Two everyday habits break it: down-sampling the “no” rows, and counting purchases before they have arrived.
- Choosing the label: clicks, kept orders and the north starA ranking model learns to predict whatever its label says. Label clicks and it learns which photos people click; label kept orders and it learns what people are glad they bought. Here the same shop is trained both ways, then tested for a few days and for four weeks.
- Cold start: new products and new shoppersA model that learns from clicks knows nothing about a product listed today or a shopper who just signed up. Give new products content features so they start next to similar ones, and give new shoppers a fallback row whose first clicks hand the row over to them.
- From raw files to search and graphELT for documents: keep the raw files, parse them, check them, clean them, give them structure, then chunk, embed, index and link them into a graph. Then keep it all fresh as files change, and keep it from outgrowing its machines.
- Embeddings: turning text into vectorsAn embedding model turns each piece of text into a list of numbers that stands for its meaning. See what happens inside, and why every vector must remember which model made it.
- Evaluating a ranker without shipping itEvery A/B test costs weeks and real shoppers. Off-policy evaluation estimates how a new ranker would do from the live ranker’s logs, by reweighting each logged visit by one over the chance it was shown. Run on the shop’s seeded shoppers: right on average, wobbly, and blind where the old ranker never looked.
- Explore and exploit: give new products a fair tryA recommender that always shows what it already knows is best never learns about anything new. Bandit policies (epsilon-greedy, UCB, Thompson sampling, a fresh-item boost) spend a few showings on products they are unsure about, and the run shows what that costs today and pays later.
- Feature stores: the same numbers for training and servingA model learns from features of the past and is fed the same features live. See how a feature store keeps the future out of training with a point-in-time join, and serves fresh values in milliseconds.
- Feedback loops: a recommender that learns only from itselfA recommender trains on the rows it showed. Whatever it shows gets clicks and so looks good; whatever it stops showing gets no data and fades. Run day after day, the row narrows, a few products take most of the views, everyone’s row looks the same, and shoppers with less common tastes lose most. A share of random slots keeps the loop open.
- Graph databases: follow the links, not the joinsWhen the question is about connections (friends of friends, who bought what, how two things are linked), a graph database stores the links themselves and walks them. See the same recommendation as SQL joins and as a graph walk, and what each reads.
- GraphRAG: answers about the whole collectionPlain RAG finds the few passages closest to a question. That fails for questions about everything at once. GraphRAG builds a graph of the things your documents mention, groups it into communities, summarises each, and answers big questions from all the summaries.
- Guardrails and prompt injectionAn agent that reads web pages can read an order planted by a stranger, and the model cannot reliably tell it from yours. See one hidden instruction try to move money, then the layers that stop it: fetched text marked as data, only the tools the task needs, a check in code, and a person for money.
- Human approval gatesSome actions are too important for a model alone. Save the exact action, let a named person approve it, check again just before acting, and report only what really happened.
- Hybrid search: keywords and meaningKeyword search finds exact words; vector search finds meaning. Run both, merge their rankings fairly, and hand the best few passages on.
- Hybrid RAG: keywords, vectors and a graphKeyword search finds exact codes, vector search finds the same idea in other words, a graph follows links between things. Each misses what the others find. Hybrid RAG runs them side by side and merges their lists by rank.
- Knowledge graphs: facts, meaning and a reasonerStore facts as triples, say what the words mean in an ontology, let a reasoner write down what follows, and ask with SPARQL. See why a question that finds nothing in the raw facts finds the right products once the rules are applied.
- LLM inference: prefill, decode and the KV cacheA language model answers one token at a time. See why the first token is slow and the rest are quick, why GPU memory runs out before the arithmetic does, and how paged memory lets one GPU serve far more people.
- MCP tool governanceMCP lets an app use tools from servers other people wrote. Learn the handshake and the calls, and the rules that keep those tools from turning against you.
- Evaluating a new model before it goes liveA new model looks better on average. Is it? See how a team tests it fairly on unseen data, checks the groups an average can hide, and lets rules written in advance decide.
- Batching: many requests, one model runA GPU handles many inputs almost as fast as one. See how a server gathers requests into a batch, and how language models refill batch slots every step.
- Model serving: a model behind an APIA trained model is just a file of numbers until something loads it, checks every request, queues work fairly and returns each answer to the right caller. Follow one fraud check through.
- Multi-agent systems: a lead and its teamOne agent loops: think, act, observe. When a job has separate parts, a lead agent can hand them to workers that run at once, with a critic checking their work. See when that pays, and what it costs.
- Multimodal models: how a model sees a photoA language model reads tokens. To read a photo, the photo is cut into small squares, and each square becomes a token next to the words. See what that costs, why to shrink photos first, and why words inside a picture must never be obeyed.
- Multimodal RAG: charts, scans and picturesReal documents hold charts, tables drawn as pictures and scanned pages. Text extraction loses them. Caption the pictures, pass the raw image to a model that can see, or search the page images directly.
- Offline metrics: precision, recall, NDCG, MRR and AUCBefore a new ranker ships, it is scored on logged data: did the products people wanted land near the top? Five common scores on one row of slots, in plain words. Then the classic surprise: a ranker that wins offline is flat online, because the log only holds what the old ranker chose to show.
- Position bias: the top slot gets clicks whatever it showsShoppers click what sits near the top of a row more, whatever it is, so a click log mixes how good a product is with where it was shown. Train on it as it is and the model learns that the top slot is good. Measure the slot’s pull, then take it out: a random slice, inverse propensity weighting, or the slot as an input set to slot 1 when serving.
- AI-powered search: rewrite the query, re-rank the resultsCustomers type short, misspelt questions in their own words. Fix and widen the query before searching, merge the results, then let a slower, smarter model re-order only the top few. That funnel is what “AI-powered search” usually means.
- RAG ingestion: preparing documentsBefore an assistant can answer from your documents, they must be cut into findable pieces and indexed two ways, and a new version must go live all at once.
- RAG, long context or a cache?Models now read hundreds of thousands of tokens, so why retrieve at all? Send a few chunks, send everything, or send everything once and cache it: each choice trades cost, completeness and freshness. See all three on one small knowledge base.
- RAG: answer from your documentsRetrieval-augmented generation: look up the right passages for this user, give them to the model as evidence, and release only answers whose citations check out.
- Re-ranking the row: dedup, seller caps and diversityA ranker scores products one at a time, so its top ten can be the same pan in four colours. A re-ranker judges the whole row: it drops near-copies, caps each seller and picks for variety (MMR). Shoppers who tire of repeats click more on the varied row, even though the ranker expected fewer.
- Vector indexes: exact, HNSW and IVFFinding the nearest vectors by measuring every one is exact but slow. See inside the two indexes databases use instead, HNSW and IVF, and how to check they still find the right answers.
Security & privacy 35 lessons
- Authentication and authorizationAn API that trusts a user id from the client leaks everything. Prove who is calling with a hashed password and a session or signed token, keep tokens short and rotate refresh tokens, then check on every request that this user may touch this row.
- OAuth 2.0 and OpenID ConnectGive an app a limited, revocable right to your data without your password: roles, scopes and consent, the right grant for each client, how APIs check tokens, and rotating signing keys without an outage.
- Cryptography fundamentalsOne message through five machines: encoding hides nothing, a hash has no key, AEAD encryption hides and protects, a MAC proves integrity, a signature proves origin to anyone. Real systems agree a key with asymmetric crypto and move data with symmetric; nonce reuse, weak randomness and homemade ciphers are how it breaks.
- Encryption in transit and at restA sniffed Wi-Fi or a stolen backup can expose every customer. TLS protects data on the network; AES-256-GCM with keys in a KMS protects it on disk and in backups. Envelope keys, rotation and crypto-shredding make it work at scale, and none of it stops an attacker who goes through the app.
- Security in design interviewsThe capstone of the security shelf: raise authentication, authorisation and data protection unprompted in each phase of a 45-minute interview, overlay trust boundaries and STRIDE on a URL shortener and a payment system, and close with the residual risk.
- Access control models: ACL, RBAC, ABAC, ReBACLogin says who; authorization says what they may do. One docs app asked the same question four ways: per-document lists, roles, attribute rules and Zanzibar relationship tuples. Then one decision service, its cache, the new enemy problem and the consistency tokens that solve it.
- Adversary emulation and purple teamingWould your detections fire against a real attacker? Map an intrusion onto MITRE ATT&CK and the kill chain, replay it one technique at a time with red and blue in one room until each alert fires, and watch detections drift over a year unless they are tested like code.
- Agentic AI securityAn agent with tools, memory and credentials turns a fooled model into a leak, a poisoned tool or a bill. See the lethal trifecta and why removing one leg stops it, a toxic flow through MCP tools stopped by a scoped token, a poisoned tool description caught by pinning and review, memory poisoning over two weeks, and a runaway loop capped by a budget.
- API securityOne shop API, attacked the ways APIs really are: ids that leak, a profile update that grants admin, a reply that carries password hashes, admin routes any customer can call, a loop that drains the database, bots that buy every pair, and a forgotten v1. Each is played request by request, then fixed.
- Business logic flaws and race conditionsA checkout loses money to requests that are each valid: a confirm call that skips payment, a negative quantity, a coupon stacked three times, two redeems of one gift card at once, a retried refund, a script with fresh keys, and a catch block that fails open. Each is played step by step, then fixed on the server.
- CI/CD pipeline securityThe pipeline holds the keys to production, so it is a target. Gates at each stage catch what their checks can see; SHA-pinned actions, safe triggers, least-privilege tokens, isolated caches and OIDC federation keep untrusted code and stolen keys out of the release.
- Cloud IAM: roles, policies and temporary credentialsEvery cloud API call is checked by IAM. Principals and JSON policies, the evaluation order (default deny, explicit deny wins), blast radius and least privilege, SCPs and boundaries, why a leaked long-lived key lasts weeks and a role credential minutes, and workload identity with no stored secret.
- Cloud security posture: shared responsibility, guardrails and attack pathsWho secures which layer in IaaS, PaaS and SaaS; a public bucket racing the scanner bots; IMDSv2 against SSRF; landing-zone guardrails that even an admin cannot switch off; and CSPM, CIEM, CWPP and CNAPP as four lenses that meet on one attack path.
- Compliance for engineersCompliance rules change architecture and daily work: PCI DSS scope follows the card number until hosted fields and tokens shrink it, payment-page scripts must be pinned, SOC 2 Type II tests months of evidence, and company traits decide which of GDPR, HIPAA, NIS2, DORA and the CRA apply. Educational, not legal advice.
- DDoS and bot defenceA flood that fills one origin's port is split across anycast edge sites; SYN cookies empty a full backlog; a hidden origin cannot be bypassed; WAF rules and per-IP limits leak while bot scores hold; HTTP/2 Rapid Reset is capped per connection; and an autoscaler pays for every bot it lets in.
- DNS and email security: forged answers, lost names, spoofed mailNames are an attack surface: forged DNS answers against a resolver and the DNSSEC signatures that make them useless, DoH for privacy, a dangling CNAME taken over on a sped-up clock, the Dyn 2016 outage and a second provider, and SPF, DKIM and DMARC deciding what happens to a spoofed invoice.
- Ethical hacking and the lawThe same request can be a finding in a report or a crime. See what turns one into the other: written permission from the right person, a scope fence, a test window and a minimal proof; what US, UK and EU law say; hat colours against real outcomes; and how to report a bug safely. Educational, not legal advice.
- Incident responseWhen an alert turns out to be real, a practised response limits the damage: confirm and scope it, contain every door the attacker holds, keep the evidence, clean up, recover, tell whoever the law says to tell, and feed the lessons back.
- Kubernetes security: admission, network policy, RBAC, signatures and runtimeFive gates around a cluster: Pod Security admission refuses dangerous pod specs, default-deny NetworkPolicy with one allow per real flow, RBAC that keeps a stolen service-account token small, image signatures checked before a pod runs, and runtime rules that catch a shell in a container.
- MFA and passkeysA right password is not proof of the right person. Leaked passwords get replayed; a second factor stops them, but codes can be phished and pushes worn down. Passkeys sign a challenge bound to the site, and recovery must be as strong as sign-in.
- Network segmentation and zero trustSplit the network into tiers, gate every packet with NACLs and security groups, give each workload its own allow-list, close admin ports, and replace "inside the VPN" with a policy check on every request.
- The OWASP Top 10Our own shop, attacked with permission one category at a time: a changed id, a glued SQL string, a URL that points inward, settings left open, an old library, a breach nobody saw, an error that fails open. Each is played request by request, then fixed.
- Password storage and credential stuffingA stolen users table should not hand over passwords. Plain text, encryption and fast hashes fail; a salt per user and a slow, memory-hard hash like Argon2id turn cracking into years. NIST-style length and breached-password checks stop weak choices, and rate limits keep stuffing from melting the login.
- Penetration testingAn authorised two-week test of our own shop on a sped-up clock: scope and rules of engagement, recon, scanning, one chained finding proven gently, a report with severity, evidence and fixes, and a retest. Black, grey or white box changes how much the same two weeks find.
- PKI and the certificate lifecycleA certificate binds a public key to names, signed through a chain up to a root in the trust store. Watch the browser check it, then automate issuance with ACME as lifetimes drop to 200, 100 and 47 days, alert when the robot breaks, and use Certificate Transparency to catch a rogue CA like DigiNotar.
- Post-quantum migrationTraffic recorded today can be decrypted once a large quantum computer exists, so key exchange moves first: hybrid X25519MLKEM768 puts two locks on one door for about 1.2 KB more per handshake. Then comes a crypto inventory, crypto agility, and signatures, which are larger and later.
- Privacy engineeringPersonal data is copied into caches, logs, warehouses, vendors and backups. Privacy engineering keeps a map of every copy, erases on request across all of them (crypto-shredding the ones that cannot be edited), collects less, keeps it shorter, and knows that pseudonymised data is still personal.
- Secrets managementA password in config.yml spreads to git history, CI logs, image layers and log lines. Push protection stops keys at the door, a secret manager holds the one copy, dynamic credentials expire by themselves, two valid versions make rotation painless, and platform identity removes the first secret.
- Security logging and detectionLog the security events that matter and never the secrets, ship them off the box into a SIEM, and turn them into alerts with rules written as code. Then make sure a person acts on each alert in time: detection only counts when someone responds.
- Service-to-service authenticationInside the network nobody should be trusted for free. Services prove who they are with short-lived tokens or mTLS certificates named by SPIFFE IDs, renewed automatically, and policies say who may call whom.
- Single sign-on (SSO)One identity provider signs people in to every app with SAML or OpenID Connect: one password and MFA, a second app for free, logout that reaches every app, and SCIM so a leaver loses access in minutes, not weeks.
- Software supply chain securityThe code you did not write, attacked the ways it really has been: a malicious patch inside a version range, a public package with an internal name, a maintainer takeover that hid in a tarball, a signed release from a hijacked pipeline, and a worm that publishes itself. Each is played on a sped-up clock, then fixed.
- Threat modellingBefore building, draw how data moves, mark where trust changes, and ask STRIDE’s six questions of each part. Rate what you find, fix the worst first, accept the rest on purpose, and repeat for every big change.
- Vulnerability managementA flaw in a library three levels down is still your flaw. A CVE id names it, CVSS rates it, KEV and EPSS say whether it is exploited; an SBOM, a scanner, a patch SLA, a WAF rule and bot pull requests with tests shrink the exposure window from days to hours.
- Web security basicsThe browser keeps scripts to their own origin and cookies to their own site, but sends requests anywhere. CSRF, XSS, CORS mistakes and clickjacking live in those gaps; SameSite, CSRF tokens, encoding, CSP and a few headers close them.