Interview Prep: Behavioural, SQL and CS Fundamentals
The SDE II bar round by round, STAR and an eight-story bank with a worked example, SQL with window functions and classic patterns, and quick references for operating systems, networking and databases.
00Interview prep atlas: rounds and routes
Everything outside the DSA, ML and system design sheets that a software or ML engineering loop still tests: the SDE II bar, behavioural stories, SQL, and computer-science fundamentals (operating systems, networking, databases). Hover diagram boxes for explanations.
Interview prep topic atlas#
How to use this sheet#
- Start with the SDE II bar so you know what "good" looks like in each round.
- Build your story bank early: eight stories cover almost every behavioural question.
- Drill SQL patterns by writing them, not reading them; window functions come up most.
- Skim the fundamentals the week before; they show up as follow-ups inside system design.
Which round needs work first?#
Check yourself 2 questions
What is the first gate in the ladder?
Show answer
Can you solve most medium problems in about 25 minutes? If not, work on coding first.
If coding, design and stories are all ready, what is left?
Show answer
Polish: SQL, CS fundamentals and full mock loops with feedback.
Takeaway Fix the earliest gate first: coding speed on mediums, then end-to-end design, then eight STAR stories, then polish with SQL, fundamentals and mocks.
01The SDE II bar: what each round is scoring
common published rubrics and interviewer guides (Google, Amazon, Meta engineering levels; Gergely Orosz, The Software Engineer's Guidebook); levels and wording vary by company.
SDE II expectations by round#
| Round | Meets the bar | Above the bar | Below the bar |
|---|---|---|---|
| Coding | Optimal approach largely unprompted; clean, runnable code for a medium in ~25 min; tests own code | Handles follow-ups (streaming, scale, a new constraint) and explains trade-offs crisply | Needs heavy hints, silent coding, untested or non-running code |
| System design | Clarifies scope, estimates, clean end-to-end design, two solid deep dives, names failure modes | Drives the conversation, quantifies trade-offs, raises operational concerns unprompted | Jumps to boxes, no numbers, can't go deep on any component |
| Low-level design | Clear entities and responsibilities, runnable core, extensible via interfaces | Concurrency and edge cases handled, tests sketched | God classes, patterns for their own sake, no working code |
| ML depth (ML engineer) | Picks sensible baselines and metrics, explains models and failure modes, knows serving and monitoring | Connects offline metrics to business impact; production stories with numbers | Model-zoo answers with no data, metric or deployment thinking |
| Behavioural | Owned a feature or service end to end; handled conflict and ambiguity; measurable results | Led cross-team work, mentored others, changed a team's process | "We" stories with no personal role, no outcome, blames others |
SDE I executes well-defined tasks; SDE II owns a well-defined area end to end with little supervision; senior engineers set direction across teams. Interviewers look for evidence of that scope in every round.
Check yourself 2 questions
What does meeting the bar look like in an SDE II coding round?
Show answer
Reaching the optimal approach largely unprompted, clean runnable code for a medium in about 25 minutes, and testing it yourself.
What separates SDE I, SDE II and senior?
Show answer
SDE I executes defined tasks, SDE II owns a defined area end to end, seniors set direction across teams.
Takeaway SDE II owns a defined area end to end with little supervision; every round looks for evidence of that scope.
Signals interviewers write down#
- Problem solving: asks clarifying questions, considers alternatives, explains why the chosen approach wins.
- Communication: thinks aloud, checks in at decision points, summarises before coding.
- Code quality: readable names, small functions, handles edge cases, correct complexity.
- Verification: dry-runs, picks tests that could break the code, fixes bugs calmly.
- Ownership and scope: stories show you deciding, not just doing what you were told.
- Write-ups are evidence-based: say the thing you want written down ("I'd pick a heap because…").
Check yourself 2 questions
Name the five signal areas interviewers record.
Show answer
Problem solving, communication, code quality, verification, and ownership and scope.
Why say your reasoning aloud, like 'I'd pick a heap because…'?
Show answer
Write-ups are evidence-based; unsaid reasoning can't be credited.
Takeaway Problem solving, communication, code quality, verification and ownership; write-ups are evidence-based, so say what you want written down.
Planning an interview loop#
| Weeks out | Focus |
|---|---|
| 8–6 | Coding patterns daily (2 timed problems); start the story bank |
| 6–4 | System design: one design every 2–3 days, out loud; ML depth or LLD for your role |
| 4–2 | Mock interviews with feedback; SQL and fundamentals review |
| Last week | Light practice, company research, questions to ask, sleep |
Record mocks or write a short self-review after each: what did I get stuck on, and what did I say that I wish I hadn't?
Check yourself 2 questions
What is the focus six to four weeks before the loop?
Show answer
System design, one design every two or three days out loud, plus ML depth or LLD for your role.
What should you do after every mock?
Show answer
Write a short self-review: where you got stuck and what you wish you hadn't said.
Takeaway Eight weeks out: coding and story bank; then system design; then mocks with SQL and fundamentals; last week light practice and sleep.
02Behavioural rounds: STAR and the story bank
Amazon Leadership Principles interview guidance; "STAR method" guides from university career services; Gayle Laakmann McDowell, Cracking the Coding Interview (behavioural chapter).
STAR, with timing#
| Part | Share of answer | What to say |
|---|---|---|
| Situation | ≈ 10% | Team, product, scale, why it mattered (two sentences) |
| Task | ≈ 10% | Your goal or responsibility, and the constraint (deadline, risk) |
| Action | ≈ 60% | What you did, step by step, including the decisions and trade-offs |
| Result | ≈ 20% | Numbers (latency, cost, revenue, incidents), what you learned, what changed afterwards |
Aim for two to three minutes, then stop and let them dig. Say "I", not "we", for your part. Have a follow-up ready: what would you do differently?
Check yourself 2 questions
Which STAR part should take most of the answer?
Show answer
Action, about 60%: what you did, with decisions and trade-offs.
How long should a STAR answer run before you stop?
Show answer
About two to three minutes, then let them dig.
Takeaway Situation and task about 20%, action about 60%, result about 20%; two to three minutes, 'I' not 'we'.
The story bank: eight stories, many questions#
| Story theme | Answers questions about |
|---|---|
| Hardest technical problem | Deep dive, debugging, persistence |
| A project you owned end to end | Ownership, delivery, prioritisation |
| A conflict or disagreement | Disagree and commit, influence without authority |
| A failure or mistake | Learning, accountability, incident handling |
| Ambiguous or changing requirements | Dealing with ambiguity, bias for action |
| Tight deadline or trade-off | Scope cuts, quality vs speed |
| Helping or mentoring someone | Teamwork, raising the bar |
| Improving a process or system | Initiative, simplification, customer focus |
Write each story once in STAR with real numbers, then tag it with every theme it can answer. Most loops ask five to eight behavioural questions in total.
Check yourself 2 questions
Name four of the eight story themes.
Show answer
Any four of: hardest technical problem, owned end to end, conflict, failure, ambiguity, tight deadline, mentoring, improving a process.
How many behavioural questions do loops usually ask in total?
Show answer
About five to eight.
Takeaway Eight real stories with numbers, each tagged with every theme it can answer, cover most behavioural questions.
A worked STAR story (ML engineer)#
| Part | Example |
|---|---|
| Situation | Our fraud model's features were computed twice, in a nightly Spark job for training and in Python for online scoring; precision had dropped from 0.82 to 0.71 over a quarter. |
| Task | I was asked to find the cause and stop it recurring, without pausing the model, within one sprint. |
| Action | I sampled 5,000 transactions and compared online and offline feature values; three features differed, one by a time-zone bug. I proposed moving the feature definitions into a shared feature store, wrote the parity test, migrated the top 20 features first, and added a CI check that fails if online and offline values diverge by more than 1%. |
| Result | Precision recovered to 0.81 within two weeks, at the same recall; the parity check caught two more mismatches in the next quarter before release. The team adopted the shared definitions for all new features. |
Why it works: a measurable problem, a clear personal role, decisions explained, numbers in the result, and a lasting change. Swap in your own story; never invent one.
Check yourself 2 questions
In the worked example, what caused the precision drop?
Show answer
Training/serving skew: features computed differently offline and online, including a time-zone bug.
What lasting change made the result stick?
Show answer
A shared feature store and a CI parity check that fails if online and offline values diverge.
Takeaway A good story has a measurable problem, a clear personal role, explained decisions, numbers in the result and a lasting change.
Behavioural traps#
- "We" all the way through: the interviewer can't credit you. Separate your actions from the team's.
- No result or no numbers: estimate if exact figures are confidential ("about a third faster").
- Blaming others in conflict stories: show how you understood their view and what you did.
- A fake weakness ("I work too hard"): pick a real, minor one and what you are doing about it.
- Rambling: long situation, short action. Flip it.
- One story for everything: reuse is fine twice, not five times.
Check yourself 2 questions
What if exact result figures are confidential?
Show answer
Estimate, e.g. 'about a third faster'.
How should you fix a rambling answer?
Show answer
Shorten the situation and give the action most of the time.
Takeaway Avoid 'we' stories, missing numbers, blaming others, fake weaknesses, rambling set-ups and one story for everything.
Which story should I tell?#
Check yourself 2 questions
Which story answers a question about influencing a colleague?
Show answer
A conflict or mentoring story: their view, your action, the outcome.
What is the default story when no other branch fits?
Show answer
Ownership or hardest-problem story, with depth and measurable impact.
Takeaway Something went wrong → failure story; other people → conflict or mentoring; uncertainty or pressure → ambiguity or deadline; else ownership or hardest problem.
Questions to ask them#
- What does success look like for this role after six months?
- What is the team's biggest technical challenge right now?
- How are projects chosen and prioritised, and who decides?
- How does on-call work, and how often does it page?
- How are engineers levelled and promoted here; what separates SDE II from senior?
- (ML roles) How do models go from notebook to production, and who owns them after launch?
Ask two or three; pick ones whose answers would change your decision.
Check yourself 2 questions
Give one question to ask about the role itself.
Show answer
What does success look like after six months? (or team's biggest technical challenge, on-call, promotion criteria)
What should an ML candidate ask about production?
Show answer
How do models go from notebook to production, and who owns them after launch?
Takeaway Ask two or three questions whose answers would actually change your decision.
03SQL for interviews
PostgreSQL documentation (queries, window functions, EXPLAIN); Markus Winand, Use the Index, Luke; common SQL interview question banks.
Logical execution order#
- That's why a
SELECTalias can't be used inWHEREbut can be used inORDER BY. WHEREfilters rows before grouping;HAVINGfilters groups after aggregation.- Window functions run after grouping, so you can't filter on them in
WHERE: wrap the query in a CTE or subquery.
Check yourself 2 questions
Why can't you use a SELECT alias in WHERE?
Show answer
WHERE runs before SELECT in logical order; ORDER BY runs after, so aliases work there.
How do you filter on a window function result?
Show answer
Wrap the query in a CTE or subquery and filter outside, since windows run after WHERE.
Takeaway FROM/JOIN → WHERE → GROUP BY → HAVING → windows → SELECT → DISTINCT → ORDER BY → LIMIT.
Joins at a glance#
| Join | Returns | Typical use |
|---|---|---|
| INNER | Only matching rows on both sides | Orders with their customers |
| LEFT | All left rows, NULLs where no match | Customers including those with no orders |
| FULL OUTER | All rows from both, NULLs where unmatched | Reconciling two sources |
| CROSS | Every combination | Calendar × product grids |
| SELF | A table joined to itself | Employee → manager, consecutive events |
| Anti-join | LEFT JOIN … WHERE b.id IS NULL or NOT EXISTS | Users who never purchased |
Watch row multiplication: joining to a one-to-many table before aggregating double counts. Aggregate first, then join.
Check yourself 2 questions
How do you find users who never purchased?
Show answer
An anti-join: LEFT JOIN … WHERE right.id IS NULL, or NOT EXISTS.
Why aggregate before joining a one-to-many table?
Show answer
Joining first multiplies rows and double counts.
Takeaway Inner keeps matches, left keeps all left rows, full keeps both, cross multiplies, anti-join finds non-matches; aggregate before joining one-to-many.
Window functions#
| Function | Does | Example |
|---|---|---|
ROW_NUMBER() | Unique sequence per partition | Latest order per user: ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) = 1 |
RANK() / DENSE_RANK() | Ties share a rank; RANK leaves gaps, DENSE_RANK doesn't | Top 3 salaries per department |
LAG() / LEAD() | Previous or next row's value | Day-over-day change, time between sessions |
SUM() OVER (ORDER BY …) | Running total | Cumulative revenue |
AVG() OVER (… ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) | Moving average | 7-day rolling average |
NTILE(n) | Splits into n buckets | Customer deciles by spend |
A window keeps every row (unlike GROUP BY). PARTITION BY restarts the calculation per group; ORDER BY inside OVER defines the running order and default frame.
Check yourself 2 questions
RANK vs DENSE_RANK?
Show answer
Both give ties the same rank; RANK leaves gaps after ties, DENSE_RANK doesn't.
Which function gives day-over-day change?
Show answer
LAG (or LEAD) to read the previous or next row.
Takeaway Windows keep every row; PARTITION BY restarts per group and ORDER BY inside OVER sets the running order.
Classic query patterns#
| Ask | Pattern |
|---|---|
| Nth highest salary | DENSE_RANK() in a CTE, filter rank = N |
| Top N per group | ROW_NUMBER() OVER (PARTITION BY g ORDER BY x DESC) <= N |
| Remove duplicates | Keep ROW_NUMBER() = 1 per duplicate key |
| Consecutive days (gaps and islands) | date − ROW_NUMBER() is constant within a streak; group by it |
| Month-over-month growth | Aggregate by month, then LAG() |
| Pivot | SUM(CASE WHEN status='x' THEN 1 ELSE 0 END) per column |
| Retention or funnels | Cohort by first event, then count later events by period |
| Median | PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) |
Check yourself 2 questions
How do you solve gaps and islands (consecutive days)?
Show answer
date − ROW_NUMBER() is constant within a streak; group by that difference.
How do you remove duplicates?
Show answer
Keep ROW_NUMBER() = 1 per duplicate key.
Takeaway DENSE_RANK for Nth highest, ROW_NUMBER for top-N and dedup, date minus ROW_NUMBER for streaks, LAG for growth, SUM(CASE) to pivot.
NULL and aggregation traps#
NULL = NULLis unknown, not true: useIS NULL/IS DISTINCT FROM.COUNT(*)counts rows;COUNT(col)skips NULLs;AVGignores NULLs (it is not "treat as zero").NOT IN (subquery)returns nothing if the subquery has a NULL; preferNOT EXISTS.- A
LEFT JOINfollowed by aWHEREon the right table silently becomes an inner join; put the condition inON. - Integer division:
1/2 = 0in many engines; cast before dividing. - Every non-aggregated column in SELECT must be in GROUP BY (strict engines).
Check yourself 2 questions
Why prefer NOT EXISTS over NOT IN (subquery)?
Show answer
If the subquery contains a NULL, NOT IN returns no rows.
COUNT(*) vs COUNT(col)?
Show answer
COUNT(*) counts rows; COUNT(col) skips NULLs.
Takeaway NULL = NULL is unknown; NOT IN with a NULL returns nothing; WHERE on the right table of a LEFT JOIN makes it inner.
Indexes and EXPLAIN#
- A B-tree index helps equality, range and ORDER BY on its leading columns. A composite index on
(a, b)serves filters onaora and b, not onbalone. - Indexes are skipped when you wrap the column in a function (
WHERE LOWER(email) = …) unless you index the expression, or when the filter matches most rows. - A covering index includes every column the query needs, so the table isn't touched (index-only scan).
EXPLAIN ANALYZEshows the plan and real timings: look for sequential scans on big tables, misestimated row counts and nested loops over large inputs.- Each index speeds reads and slows writes; index for your top queries, not every column.
Check yourself 2 questions
Does an index on (a, b) help a filter on b alone?
Show answer
No; it serves a, or a and b, not b alone.
What do you look for in EXPLAIN ANALYZE?
Show answer
Sequential scans on big tables, misestimated row counts and nested loops over large inputs.
Takeaway B-trees serve leading columns; functions on the column skip the index; covering indexes avoid the table; each index slows writes.
04Operating systems quick reference
Arpaci-Dusseau, Operating Systems: Three Easy Pieces; Silberschatz, Operating System Concepts; Linux man pages.
Processes vs threads#
| Process | Thread | |
|---|---|---|
| Memory | Own address space | Shares the process's address space |
| Creation and switch cost | Higher (new page tables) | Lower |
| Isolation | A crash stays contained | A bad thread can corrupt the whole process |
| Communication | IPC: pipes, sockets, shared memory | Shared variables, guarded by locks |
- A context switch saves registers and the program counter, and for processes swaps the address space, flushing much of the TLB.
- Python's GIL lets only one thread run Python bytecode at a time: use processes (or native code) for CPU-bound work, threads or asyncio for I/O-bound work.
Check yourself 2 questions
Why is a process switch costlier than a thread switch?
Show answer
It also swaps the address space, flushing much of the TLB.
Why use processes for CPU-heavy Python?
Show answer
The GIL lets only one thread run Python code at a time.
Takeaway Processes isolate memory and crashes; threads share memory and need locks; in Python use processes for CPU work, threads or asyncio for I/O.
CPU scheduling#
| Policy | Idea | Trade-off |
|---|---|---|
| FCFS | First come, first served | Short jobs wait behind long ones (convoy effect) |
| SJF / SRTF | Shortest job (remaining) first | Best average wait, needs run-time estimates, can starve long jobs |
| Round robin | Fixed time slice each | Good response time; slice size trades overhead vs latency |
| Priority / MLFQ | Multi-level queues; demote CPU hogs | Needs ageing to avoid starvation |
| Linux CFS / EEVDF | Fair share of CPU time by weight | Default general-purpose scheduler |
Check yourself 2 questions
What is the convoy effect?
Show answer
Under first-come first-served, short jobs wait behind a long one.
What prevents starvation in priority scheduling?
Show answer
Ageing: raising the priority of jobs that have waited long.
Takeaway FCFS suffers convoys, SJF minimises average wait but starves, round robin trades slice overhead for latency, MLFQ needs ageing.
Synchronisation and deadlock#
- Mutex: one holder at a time. Semaphore: a counter allowing N holders. Condition variable: wait until a predicate is true, always in a loop.
- Race condition: the result depends on interleaving; fix with a lock or an atomic operation around the whole check-then-act.
- Deadlock needs all four: mutual exclusion, hold and wait, no preemption, circular wait. Break one, most often circular wait by acquiring locks in a global order.
- Livelock keeps threads busy without progress; starvation leaves one never served.
- Prefer higher-level tools (queues, thread pools, actors) over hand-rolled locks.
Check yourself 2 questions
Name the four deadlock conditions.
Show answer
Mutual exclusion, hold and wait, no preemption, circular wait.
Why check a condition variable's predicate in a loop?
Show answer
Wake-ups can be spurious or the condition can change before the thread runs.
Takeaway Deadlock needs mutual exclusion, hold and wait, no preemption and circular wait; break circular wait with a global lock order.
Memory: virtual memory and paging#
- Each process sees a private virtual address space; the MMU translates pages (typically 4 KB) to physical frames via page tables.
- The TLB caches recent translations; a TLB miss walks the page table, a page fault loads the page from disk or allocates it.
- Thrashing: the working set exceeds RAM and the system spends its time paging; fix by adding memory or reducing concurrency.
- Stack: per thread, automatic, small. Heap: shared, manual or garbage-collected, fragmentation risk.
- Copy-on-write makes
fork()cheap: pages are shared until one side writes. - Linux OOM killer ends a process when memory runs out; containers hit their cgroup memory limit first.
Check yourself 2 questions
Why is fork cheap?
Show answer
Copy-on-write: pages are shared until one side writes.
What is thrashing?
Show answer
The working set exceeds RAM, so the system spends its time paging.
Takeaway The MMU maps virtual pages to frames via page tables, the TLB caches translations, and thrashing means the working set exceeds RAM.
I/O models#
| Model | How | Used by |
|---|---|---|
| Blocking | Thread waits for each read or write | Simple thread-per-connection servers |
| Non-blocking + multiplexing | epoll / kqueue tell one thread which sockets are ready | Nginx, Node.js, Redis, asyncio |
| Asynchronous | Submit and get completions (io_uring) | High-performance storage and networking |
One thread with an event loop can serve tens of thousands of idle connections; CPU-heavy work still needs more cores or processes.
Check yourself 2 questions
How do Nginx, Node and Redis handle many connections?
Show answer
Non-blocking I/O with multiplexing (epoll or kqueue) on an event loop.
What can't one event loop fix?
Show answer
CPU-heavy work, which still needs more cores or processes.
Takeaway Blocking needs a thread per connection; epoll/kqueue multiplexing lets one thread serve many sockets; io_uring is truly async.
Linux commands for debugging#
| Question | Command |
|---|---|
| What's using CPU or memory? | top, htop, ps aux --sort=-%mem |
| Disk and I/O | df -h, du -sh *, iostat |
| Open ports and connections | ss -tulpn, lsof -i :8080 |
| What is this process doing? | strace -p PID, perf top |
| Logs | journalctl -u service -f, tail -f, grep |
| Network path | dig, curl -v, traceroute |
Check yourself 2 questions
Which command shows what port a process is listening on?
Show answer
ss (e.g. ss -ltnp) or lsof -i on the port.
How do you see the system calls a process is making?
Show answer
strace (or perf top for CPU hotspots).
Takeaway top/htop and ps for CPU and memory, df/du/iostat for disk, ss/lsof for ports, strace/perf for a process, journalctl for logs, dig/curl/traceroute for network.
05Networking quick reference
Kurose and Ross, Computer Networking: A Top-Down Approach; MDN web docs (HTTP); Cloudflare learning centre (DNS, TLS).
Layers, and TCP vs UDP#
| Layer (TCP/IP) | Examples |
|---|---|
| Application | HTTP, DNS, gRPC, WebSocket |
| Transport | TCP, UDP, QUIC (over UDP) |
| Internet | IP, ICMP |
| Link | Ethernet, Wi-Fi |
| TCP | UDP | |
|---|---|---|
| Connection | Handshake first | None |
| Delivery | Reliable, ordered, retransmits | Best effort, may drop or reorder |
| Control | Flow and congestion control | None built in |
| Uses | Web, databases, APIs | DNS, video calls, games, QUIC |
Check yourself 2 questions
Name the four TCP/IP layers.
Show answer
Application, transport, internet (IP), link.
Why does QUIC run over UDP?
Show answer
It builds its own reliability on top while avoiding TCP's limitations.
Takeaway TCP is connection-based, reliable and ordered; UDP is lightweight with no guarantees, suiting DNS, calls, games and QUIC.
TCP handshake and congestion#
- Three-way handshake: SYN → SYN-ACK → ACK; one round trip before data. Teardown uses FIN and ACK from each side; TIME_WAIT lingers on the closer.
- Flow control protects the receiver (advertised window); congestion control protects the network (slow start, then additive increase, multiplicative decrease; CUBIC and BBR in practice).
- Head-of-line blocking: one lost packet stalls everything behind it on that connection, which is why HTTP/3 moved to QUIC.
- Latency is bounded by round trips: connection reuse, keep-alive and fewer handshakes matter more than bandwidth for small requests.
Check yourself 2 questions
What is head-of-line blocking in TCP?
Show answer
One lost packet stalls everything behind it on that connection.
For small requests, what dominates latency?
Show answer
Round trips, so connection reuse matters more than bandwidth.
Takeaway SYN, SYN-ACK, ACK costs a round trip; flow control protects the receiver, congestion control the network; one loss blocks the whole TCP stream.
What happens when you type a URL#
- DNS: browser cache → OS cache → recursive resolver → root → TLD → authoritative server returns the IP (cached per TTL).
- TCP (or QUIC) connection to the IP, usually port 443, possibly via a CDN edge near you.
- TLS handshake: agree on keys, verify the certificate chain (TLS 1.3 takes one round trip).
- HTTP request with method, path, headers and cookies; a load balancer routes it to a server.
- Server work: application logic, caches, database queries; a response with status, headers and body.
- Rendering: the browser parses HTML, fetches CSS, JS and images (often in parallel over HTTP/2 or 3), builds the DOM and paints.
Interviewers use this to probe depth: be ready to zoom into any step (DNS caching, TLS, load balancing, caching headers).
Check yourself 2 questions
What does the recursive resolver ask, in order?
Show answer
The root, then the top-level domain, then the authoritative server.
How many round trips does a TLS 1.3 handshake take?
Show answer
One.
Takeaway DNS lookup, TCP or QUIC connect, TLS handshake, HTTP request through a load balancer, server work, then browser parse and paint.
HTTP versions and TLS#
| Version | Key change |
|---|---|
| HTTP/1.1 | Keep-alive; one request at a time per connection, so browsers open several |
| HTTP/2 | Multiplexed streams over one TCP connection, binary framing, header compression |
| HTTP/3 | Over QUIC (UDP): no TCP head-of-line blocking, faster setup, connection migration |
- TLS gives encryption, integrity and server authentication via certificates signed by a trusted CA; mTLS also authenticates the client.
- Status codes: 2xx success, 3xx redirect, 4xx client error (400, 401, 403, 404, 429), 5xx server error (500, 502, 503, 504).
- Idempotent methods: GET, PUT, DELETE (and HEAD, OPTIONS); POST is not.
Check yourself 2 questions
What problem does HTTP/3 solve that HTTP/2 doesn't?
Show answer
TCP head-of-line blocking, by running over QUIC.
What does mutual TLS add?
Show answer
It authenticates the client as well as the server.
Takeaway HTTP/1.1 one request at a time per connection, HTTP/2 multiplexes over TCP, HTTP/3 runs over QUIC; GET, PUT and DELETE are idempotent, POST isn't.
DNS, load balancers and proxies#
- DNS records: A/AAAA (address), CNAME (alias), MX (mail), TXT (verification), NS (delegation). TTL controls caching and how fast changes spread.
- L4 load balancer: routes by IP and port, fast, protocol-agnostic. L7: reads HTTP (paths, headers, cookies), can terminate TLS and do canaries.
- Forward proxy acts for clients; reverse proxy sits in front of servers (Nginx, Envoy).
- NAT maps private addresses to a public one; CIDR such as /24 means 256 addresses.
- Common ports: 22 SSH, 53 DNS, 80 HTTP, 443 HTTPS, 5432 Postgres, 6379 Redis, 9092 Kafka.
Check yourself 2 questions
What can an L7 load balancer do that L4 can't?
Show answer
Route by path or header, terminate TLS, run canaries.
Forward vs reverse proxy?
Show answer
A forward proxy acts for clients; a reverse proxy sits in front of servers.
Takeaway L4 balancers route by IP and port; L7 read HTTP to route by path, terminate TLS and run canaries; DNS TTL sets how fast changes spread.
06Databases (DBMS) quick reference
Kleppmann, Designing Data-Intensive Applications; Silberschatz, Database System Concepts; PostgreSQL documentation (MVCC, isolation).
ACID and isolation levels#
| Property | Meaning |
|---|---|
| Atomicity | All or nothing (undo or write-ahead log) |
| Consistency | Constraints hold before and after |
| Isolation | Concurrent transactions don't see each other's partial work |
| Durability | Committed data survives a crash (WAL fsync) |
| Level | Prevents | Still allows |
|---|---|---|
| Read committed | Dirty reads | Non-repeatable reads, phantoms |
| Repeatable read / snapshot | + non-repeatable reads | Write skew |
| Serializable | All anomalies | Nothing, at a throughput cost |
Check yourself 2 questions
Which anomaly does snapshot isolation still allow?
Show answer
Write skew.
What provides durability after a crash?
Show answer
The write-ahead log.
Takeaway Read committed stops dirty reads; repeatable read/snapshot stops non-repeatable reads but allows write skew; serializable stops all anomalies.
Normalisation#
| Form | Rule |
|---|---|
| 1NF | Atomic values, no repeating groups |
| 2NF | 1NF + no partial dependency on part of a composite key |
| 3NF | 2NF + no transitive dependency (non-key → non-key) |
| BCNF | Every determinant is a candidate key |
Normalise to avoid update anomalies; denormalise deliberately for read-heavy paths (and keep the copy in sync with events or triggers).
Check yourself 2 questions
What does 3NF remove?
Show answer
Transitive dependencies, where a non-key column determines another.
When is denormalising acceptable?
Show answer
On read-heavy paths, deliberately, keeping copies in sync with events or triggers.
Takeaway 1NF atomic values, 2NF no partial key dependency, 3NF no transitive dependency, BCNF every determinant a candidate key; denormalise deliberately.
Indexes inside the database#
- B+ tree: sorted, balanced, leaves linked; great for ranges and ordering; the default in Postgres and MySQL.
- Hash index: equality only. GIN / inverted: full-text and arrays. BRIN: huge, naturally ordered tables (time series).
- Clustered (InnoDB primary key) stores rows in index order; secondary indexes point back to the row or key.
- LSM trees (RocksDB, Cassandra) buffer writes in memory and merge sorted files: fast writes, compaction cost.
- Selectivity matters: an index on a boolean column rarely helps.
Check yourself 2 questions
Why do LSM trees give fast writes?
Show answer
They buffer writes in memory and merge sorted files later, at the cost of compaction.
Why rarely index a boolean column?
Show answer
Low selectivity: the filter matches too many rows to help.
Takeaway B+ trees for ranges, hash for equality, GIN for text and arrays, BRIN for huge ordered tables; LSM trees trade compaction for fast writes.
Locking and MVCC#
- Pessimistic locking:
SELECT … FOR UPDATEholds row locks until commit; safe under contention, risks waits and deadlocks. - Optimistic concurrency: a version column; update
WHERE version = nand retry if zero rows changed. - MVCC (Postgres, InnoDB): writers create new row versions, readers see a snapshot, so reads don't block writes. Old versions need cleanup (VACUUM in Postgres).
- Databases detect deadlocks and abort one transaction; the application must retry.
Check yourself 2 questions
How does optimistic concurrency detect conflicts?
Show answer
Update only where the version column matches; zero rows updated means retry.
What must the application do about deadlocks?
Show answer
Be ready to retry, since the database aborts one transaction.
Takeaway Pessimistic locks hold rows until commit; optimistic concurrency checks a version; MVCC lets reads not block writes, with VACUUM cleaning old versions.
SQL vs NoSQL#
| Need | Lean towards |
|---|---|
| Transactions, joins, constraints, ad-hoc queries | Relational (Postgres, MySQL) |
| Huge write volume, key-based access, wide rows | Wide-column (Cassandra, DynamoDB) |
| Flexible documents, nested data | Document (MongoDB) |
| Caching, counters, leaderboards | Key-value in memory (Redis) |
| Relationships as the query (friends of friends) | Graph (Neo4j) |
| Search, relevance | Search engine (Elasticsearch, OpenSearch) |
Start relational unless a specific access pattern or scale rules it out; you can add a specialised store later.
Check yourself 2 questions
When does a wide-column store like Cassandra fit?
Show answer
Huge write volumes with key-based access.
Which store suits friends-of-friends queries?
Show answer
A graph database.
Takeaway Default to relational for transactions, joins and ad hoc queries; pick NoSQL for a specific access pattern or scale.
Replication and sharding in one card#
- Replication copies data for availability and read scale: leader–follower (simple, replica lag), multi-leader (conflicts), leaderless quorums (R + W > N).
- Sharding splits data for write scale: by range (good for scans, hot spots) or hash (even, no range queries); consistent hashing eases rebalancing.
- Read-your-writes after replication: read from the leader for a short window, or track the user's last write position.
- Full detail lives on the HLD sheet's data section.
Check yourself 2 questions
What is the leaderless quorum rule?
Show answer
Reads plus writes must exceed the replica count (R + W > N).
How do you give read-your-writes with replicas?
Show answer
Read from the leader for a short window or track the user's last write position.
Takeaway Replication scales reads and availability; sharding scales writes; range shards scan well but hot-spot, hash shards spread evenly but lose ranges.
07Before the loop
The day-before checklist#
- Story bank re-read: eight stories, each with numbers and a lesson.
- Two warm-up coding problems you have solved before, timed.
- One system design sketched out loud end to end.
- Company and team research; three questions to ask.
- Logistics: links, IDE or whiteboard tool tested, water, a quiet room, sleep.
Check yourself 2 questions
Which coding problems should you warm up with the day before?
Show answer
Two you've solved before, timed.
What logistics should be sorted?
Show answer
Links, the coding tool tested, water, a quiet room, and sleep.
Takeaway Re-read the story bank, two warm-up problems, one design out loud, finish research and questions, sort logistics and sleep.
During every round#
- Restate the problem and confirm scope before solving.
- Think aloud; say trade-offs as decisions ("I'll use X because Y").
- Test before saying "done".
- If stuck, say what you know and ask a focused question.
- Leave two minutes for their questions, and use them.
Check yourself 2 questions
What should you do before solving?
Show answer
Restate the problem and confirm the scope.
What should you do when stuck?
Show answer
Say what you know and ask one focused question.
Takeaway Restate and scope, think aloud with trade-offs as decisions, test before saying done, ask one focused question when stuck, keep time for theirs.
About this sheet#
A compact reference for the non-DSA parts of software and ML engineering interviews, written from the sources named on each section. Levels, rubrics and processes differ between companies; treat the expectations as a common pattern, and adapt your stories to your own real experience.