CS Fundamentals Interview Questions: Operating Systems, Networking, Databases and Concurrency
Computer science fundamentals interview questions with answers covering the four areas software engineering interviews keep coming back to: operating systems (processes, threads, memory, scheduling, file systems), computer networking (TCP/IP, DNS, HTTP, TLS), databases (indexes, transactions, isolation levels, normalization, replication) and concurrency (locks, deadlocks, race conditions, async). Answers are written to be explained out loud in a few minutes, and the classic exercises (CPU scheduling, page replacement, banker’s algorithm, producer-consumer, LRU cache, rate limiter, subnetting) are runnable, tested Python in src/osnet.py.
Last reviewed: December 2026. Protocol details reference current RFCs (TCP: RFC 9293, QUIC: RFC 9000, HTTP/3: RFC 9114, TLS 1.3: RFC 8446).
git clone https://github.com/Ralpberry-Labs/cs-fundamentals-interview-questions
cd cs-fundamentals-interview-questions
python3 -m unittest discover -s tests -v # 12 tests, standard library only
Table of Contents
- Who Asks These Questions and How
- Study Roadmap
- Part 1: Operating Systems
- Part 2: Computer Networking
- Part 3: Databases
- Part 4: Concurrency
- Part 5: Distributed Systems Basics
- Numbers Every Engineer Should Know
- Runnable Exercises
- Best Resources (Free and Paid)
- FAQ
- Where to Go Next
- Contributing
- License
Who Asks These Questions and How
- New grad and intern interviews often include a fundamentals round or rapid-fire questions (“process vs thread?”, “what happens when you type a URL?”).
- Backend, infrastructure, SRE and systems roles go deeper: memory, I/O, TCP behavior, isolation levels, locking.
- System design rounds assume this knowledge: you can’t design a cache or a database layer without knowing how indexes, replication and consistency work.
- Embedded, OS and database companies ask the deepest versions (virtual memory internals, lock-free structures, storage engines).
The best answers are short, precise, and include why it matters in practice, for example “that’s why a missing index turns a 2 ms query into a 2 s table scan.”
Study Roadmap
| Week | Topic | Read | Do |
|---|---|---|---|
| 1 | Processes, threads, scheduling, system calls | OSTEP virtualization chapters | Run the scheduling and page-fault exercises; predict outputs first |
| 2 | Memory, virtual memory, file systems | OSTEP memory and persistence chapters | Explain a page fault end to end out loud |
| 3 | Networking: layers, TCP, UDP, DNS, HTTP, TLS | Computer Networks: A Systems Approach, High Performance Browser Networking | Trace curl -v https://example.com, explain each line |
| 4 | Databases: indexes, transactions, isolation | Use The Index, Luke, PostgreSQL isolation docs | Reproduce a lost update and fix it with SELECT ... FOR UPDATE |
| 5 | Concurrency | The Little Book of Semaphores, OSTEP concurrency chapters | Implement producer-consumer and a reader-writer lock |
| 6 | Distributed basics and review | Cambridge Concurrent and Distributed Systems notes | Mock interview: 30 rapid-fire questions from this page |
Two weeks is enough for a refresh if you studied these in school; six weeks if you’re self-taught.
Part 1: Operating Systems
Q1. What does an operating system do?
It virtualizes hardware (each process thinks it has its own CPU and memory), manages shared resources fairly and safely (scheduling, memory, devices), and provides abstractions like files, sockets and processes through system calls. It also protects processes from each other and the kernel from processes.
Q2. Process vs thread?
| Process | Thread | |
|---|---|---|
| Memory | Own address space | Shares the process’s address space |
| Creation cost | Higher (new page tables, resources) | Lower |
| Communication | IPC: pipes, sockets, shared memory | Shared variables (needs synchronization) |
| Failure isolation | A crash usually affects only that process | A crash takes down the whole process |
| Has its own | PID, address space, file descriptor table | Stack, registers, program counter, thread-local storage |
Example: browsers run sites in separate processes for isolation, while a web server uses threads or async tasks within a process for cheap concurrency.
Q3. What is a context switch and why is it expensive?
The kernel saves one thread’s CPU state (registers, program counter, stack pointer) and loads another’s. Switching between processes may also change the address space, which can flush or invalidate TLB entries. The direct cost is microseconds; the bigger indirect cost is cold caches. Too many runnable threads means time lost to switching instead of work.
Q4. User mode vs kernel mode? What is a system call?
The CPU runs application code in a restricted mode that can’t touch hardware or other processes’ memory. A system call (read, write, open, fork, mmap) is a controlled trap into the kernel, which checks arguments, does the privileged work, and returns. System calls cost far more than a normal function call, which is why buffered I/O batches many small writes into one write call.
Q5. What happens on fork() and exec()?
fork() creates a child process that is a copy of the parent. Modern kernels use copy-on-write: parent and child share physical pages marked read-only until one writes, so fork is cheap. exec() replaces the current process image with a new program. Shells do fork, then exec in the child.
Q6. Explain the process states.
New, ready (waiting for a CPU), running, blocked/waiting (on I/O, a lock, a timer), and terminated. A terminated child whose parent hasn’t collected its exit status is a zombie; a running process whose parent died is an orphan and gets adopted by init.
Q7. Compare CPU scheduling algorithms.
| Algorithm | Idea | Good | Bad |
|---|---|---|---|
| FCFS | Run in arrival order | Simple, fair in order | Convoy effect: short jobs wait behind long ones |
| SJF / SRTF | Shortest (remaining) job first | Minimizes average waiting time | Needs job length; can starve long jobs |
| Round robin | Fixed time slice, rotate | Good response time | Too small a quantum wastes time switching |
| Priority | Highest priority first | Expresses importance | Starvation; fix with aging |
| Multilevel feedback queue | Jobs move between priority queues based on behavior | Favors interactive jobs without knowing lengths | Complex to tune |
| CFS / EEVDF (Linux) | Fair share of CPU weighted by niceness; EEVDF replaced CFS as the default in Linux 6.6 | Fairness plus latency control | More complex |
With jobs A(arrives 0, runs 8), B(1, 4), C(2, 2): FCFS waiting times are A=0, B=7, C=10; non-preemptive SJF gives A=0, B=9, C=6. Run schedule() in src/osnet.py to see round robin too.
Q8. What is virtual memory?
Each process gets its own large, contiguous-looking address space. The hardware MMU translates virtual addresses to physical ones using page tables maintained by the kernel, typically with 4 KiB pages. Benefits: isolation between processes, memory larger than RAM (via swapping), sharing (libraries, copy-on-write), and memory-mapped files.
Q9. What is a TLB?
The translation lookaside buffer caches recent virtual-to-physical translations so the CPU doesn’t walk the page table on every access. TLB misses are expensive, which is one reason huge pages (2 MiB/1 GiB) help memory-heavy workloads like databases.
Q10. What is a page fault? Minor vs major?
An access to a virtual page that isn’t currently mapped in physical memory traps to the kernel. Minor: the page is in memory but not mapped for this process (e.g. shared library, copy-on-write), cheap. Major: the page must be read from disk (swap or file), slow. An access to an invalid address raises a segmentation fault instead.
Q11. Compare page replacement policies.
FIFO evicts the oldest page and can suffer Belady’s anomaly (more frames causing more faults). LRU evicts the least recently used and approximates the optimal policy well; real kernels use approximations (clock algorithm, active/inactive lists). OPT (evict the page used furthest in the future) is the theoretical best and is used only as a benchmark. The test suite reproduces Belady’s anomaly: reference string 1 2 3 4 1 2 5 1 2 3 4 5 gives 9 faults with 3 FIFO frames and 10 with 4.
Q12. What is thrashing?
The working sets of running processes don’t fit in RAM, so the system spends most of its time paging instead of working. Fixes: add memory, run fewer processes, reduce working sets.
Q13. Stack vs heap?
The stack holds function frames (locals, return addresses), grows and shrinks automatically, is per-thread and fast, and is limited in size (deep recursion overflows it). The heap holds dynamically allocated memory with arbitrary lifetimes, managed by an allocator or garbage collector, and can fragment.
Q14. What is a memory leak in a garbage-collected language?
Memory that is still reachable but no longer needed: a growing cache without eviction, listeners never removed, global collections, closures capturing large objects. The GC can only free unreachable objects.
Q15. How does a file system store a file?
Metadata lives in an inode (permissions, size, timestamps, pointers to data blocks or extents); directory entries map names to inode numbers. Writes go to the page cache first and are flushed later, so fsync is needed for durability. Journaling (ext4, XFS) or copy-on-write (Btrfs, ZFS) keeps the file system consistent after a crash.
Q16. What is an interrupt?
A signal from hardware (a network packet arrived, a disk read completed, a timer fired) that makes the CPU pause and run a handler in the kernel. Timer interrupts are what let the scheduler preempt a running thread.
Q17. Blocking, non-blocking, and asynchronous I/O?
Blocking I/O puts the thread to sleep until data is ready. Non-blocking I/O returns immediately with “would block,” and readiness APIs (epoll on Linux, kqueue on BSD/macOS) tell you which of many sockets are ready, letting one thread handle thousands of connections (the event loop model of Node.js, nginx, Python asyncio). Completion-based async I/O (io_uring on Linux, IOCP on Windows) submits operations and gets notified when they finish.
Q18. What is DMA?
Direct memory access lets devices copy data to and from memory without the CPU moving every byte; the CPU is interrupted only when the transfer completes.
Q19. What are containers at the OS level?
Ordinary processes isolated with namespaces (what they can see: PIDs, network, mounts, hostname, users) and limited with cgroups (how much CPU, memory, I/O they can use). They share the host kernel, unlike VMs.
Part 2: Computer Networking
Q20. Explain the OSI and TCP/IP models.
| OSI layer | TCP/IP layer | Examples |
|---|---|---|
| 7 Application, 6 Presentation, 5 Session | Application | HTTP, DNS, TLS (sits between), SSH |
| 4 Transport | Transport | TCP, UDP, QUIC (over UDP) |
| 3 Network | Internet | IP, ICMP |
| 2 Data link, 1 Physical | Link | Ethernet, Wi-Fi |
Interviewers mostly care that you can place a protocol and explain what each layer adds (ports, routing, framing).
Q21. What happens when you type a URL and press Enter?
- Parse the URL; check HSTS, caches.
- DNS resolution to an IP (browser cache, OS cache, recursive resolver, then root, TLD and authoritative servers if needed).
- Connection: TCP three-way handshake, or QUIC for HTTP/3.
- TLS handshake: certificate verification against trusted CAs, key exchange; TLS 1.3 takes one round trip (zero with resumption, with replay caveats).
- HTTP request, likely through a CDN, load balancer and reverse proxy to an application server, which may query caches and databases.
- Response: status, headers, body; browser parses HTML, fetches CSS/JS/images, builds the DOM and render tree, paints.
Go as deep as the interviewer wants on any step. A famously detailed community version: alex/what-happens-when.
Q22. TCP three-way handshake and connection teardown?
SYN (client picks initial sequence number), SYN-ACK (server acknowledges and picks its own), ACK. Teardown uses FIN and ACK from each side; the side that closes first enters TIME_WAIT to absorb delayed packets. The handshake costs one round trip before data can flow, which is why connection reuse and QUIC matter for latency.
Q23. How does TCP ensure reliable delivery?
Sequence numbers, acknowledgments, retransmission on timeout or duplicate ACKs, checksums, and ordered reassembly. Flow control (receiver’s advertised window) stops the sender from overwhelming the receiver; congestion control (slow start, congestion avoidance, algorithms like CUBIC and BBR) stops it from overwhelming the network.
Q24. TCP vs UDP?
TCP: reliable, ordered, connection-oriented byte stream, with head-of-line blocking (one lost packet stalls later data). UDP: unreliable datagrams, no connection, no ordering, minimal overhead; used for DNS, real-time media, games, and as the base for QUIC.
Q25. What is QUIC and HTTP/3?
QUIC is a transport protocol on UDP that builds in TLS 1.3 encryption, multiple independent streams (no head-of-line blocking across streams), faster connection setup, and connection migration (switching from Wi-Fi to cellular without reconnecting). HTTP/3 is HTTP over QUIC (RFC 9000, RFC 9114).
Q26. HTTP/1.1 vs HTTP/2 vs HTTP/3?
| HTTP/1.1 | HTTP/2 | HTTP/3 | |
|---|---|---|---|
| Transport | TCP | TCP | QUIC (UDP) |
| Format | Text | Binary frames | Binary frames |
| Multiplexing | No (one request at a time per connection; browsers open several) | Yes, many streams on one connection | Yes, without TCP head-of-line blocking |
| Header compression | No | HPACK | QPACK |
Q27. How does DNS work? What record types matter?
A stub resolver asks a recursive resolver, which walks from root servers to the TLD servers to the domain’s authoritative servers, caching every answer for its TTL. Key records: A, AAAA, CNAME, MX, TXT, NS, SOA, SRV, CAA. DNS mostly uses UDP port 53, falling back to TCP for large responses; DNS over HTTPS/TLS encrypts queries.
Q28. What does TLS provide and how does the handshake work?
Confidentiality, integrity and server (optionally client) authentication. In TLS 1.3 the client sends supported cipher suites and a key share; the server replies with its key share, certificate and a signature proving it holds the private key; both derive session keys via (EC)DHE, which gives forward secrecy. The client validates the certificate chain up to a trusted root and checks the hostname. Spec: RFC 8446.
Q29. Symmetric vs asymmetric encryption?
Symmetric (AES, ChaCha20) uses one shared key and is fast. Asymmetric (RSA, elliptic curves) uses a public/private key pair and is slow, so it’s used to authenticate and agree on a symmetric key, which then encrypts the data.
Q30. What is NAT?
Network address translation lets many devices share one public IPv4 address by rewriting source addresses and ports on the way out and tracking connections to map replies back. It’s why inbound connections to home devices need port forwarding, and part of why IPv6 adoption matters.
Q31. What are subnets and CIDR?
CIDR notation 10.0.1.0/24 means the first 24 bits are the network prefix: 256 addresses, 254 usable hosts in classic IPv4 (network and broadcast reserved). /26 is 64 addresses. Two hosts are on the same subnet if their addresses match under the mask. subnet_info() and same_subnet() in the code do this with Python’s ipaddress module.
Q32. What is ARP?
On a local IPv4 network, ARP maps an IP address to a MAC address by broadcasting “who has 192.168.1.5?” IPv6 uses Neighbor Discovery instead.
Q33. What’s the difference between a hub, switch and router?
A hub repeats frames to every port (obsolete). A switch forwards Ethernet frames by MAC address within a network (layer 2). A router forwards IP packets between networks (layer 3) using routing tables.
Q34. What is a socket?
An endpoint for communication identified by IP, port and protocol. A TCP connection is identified by the 4-tuple (source IP, source port, destination IP, destination port). Servers bind, listen, accept; clients connect. Beej’s Guide to Network Programming is the classic free reference.
Q35. REST vs gRPC vs WebSockets?
REST: resource-oriented HTTP with JSON, simple and cacheable. gRPC: RPC over HTTP/2 with Protocol Buffers, efficient and strongly typed, supports streaming, popular between services. WebSockets: a long-lived, full-duplex connection upgraded from HTTP, used for real-time updates in browsers.
Q36. What is a CDN?
A network of edge servers that caches content close to users, cutting latency and origin load, and often adds TLS termination, DDoS protection and edge compute.
Q37. What is head-of-line blocking?
When one delayed item holds up everything behind it: HTTP/1.1 pipelining (responses must be in order) and TCP (one lost packet stalls all streams on an HTTP/2 connection). QUIC solves the transport-level version.
Part 3: Databases
Q38. What does ACID mean?
- Atomicity: a transaction happens fully or not at all.
- Consistency: a transaction moves the database from one valid state to another (constraints hold).
- Isolation: concurrent transactions don’t see each other’s partial work (to a degree set by the isolation level).
- Durability: once committed, it survives crashes (write-ahead log flushed to disk).
Q39. Explain isolation levels and the anomalies they prevent.
| Level | Dirty read | Non-repeatable read | Phantom read | Notes |
|---|---|---|---|---|
| Read uncommitted | Possible | Possible | Possible | PostgreSQL treats it as read committed |
| Read committed | Prevented | Possible | Possible | PostgreSQL default |
| Repeatable read | Prevented | Prevented | Possible per the SQL standard | MySQL InnoDB default; PostgreSQL’s implementation (snapshot isolation) also prevents phantoms |
| Serializable | Prevented | Prevented | Prevented | Results equal some serial order |
Also know lost updates and write skew (two transactions read the same data, each makes a decision, and both write different rows, violating an invariant, e.g. two doctors both going off call). Snapshot isolation allows write skew; serializable prevents it. Reference: PostgreSQL transaction isolation.
Q40. How do you prevent a lost update (two users increment a counter)?
Use an atomic update (UPDATE t SET n = n + 1 WHERE id = ?), pessimistic locking (SELECT ... FOR UPDATE in a transaction), optimistic concurrency (a version column; update only WHERE version = ? and retry if zero rows changed), or serializable isolation with retries.
Q41. How does an index work?
Most relational indexes are B+ trees: sorted keys in a shallow, wide tree, so a lookup touches only a few pages and range scans walk leaf pages in order. Indexes speed reads but cost extra storage and slow writes. Hash indexes support only equality. Excellent free book: Use The Index, Luke.
Q42. What’s a composite index and the leftmost prefix rule?
An index on (country, city, created_at) can serve queries filtering on country, country + city, or all three, but not on city alone. Put equality columns first and the range column last.
Q43. Clustered vs non-clustered index? Covering index?
A clustered index stores table rows in index order (InnoDB’s primary key); there can be only one. A secondary index stores keys plus a pointer (or the primary key) to the row. A covering index contains every column the query needs, so the table itself isn’t read.
Q44. Why might a query not use an index?
A function or type cast on the indexed column (WHERE LOWER(email) = ... without an expression index), a leading wildcard (LIKE '%abc'), low selectivity (the planner prefers a sequential scan when most rows match), outdated statistics, or a composite index used without its leftmost column. Check with EXPLAIN / EXPLAIN ANALYZE.
Q45. What is normalization? When do you denormalize?
Normalization removes redundancy so each fact lives in one place: 1NF (atomic values), 2NF (no partial dependency on a composite key), 3NF (no transitive dependencies). It prevents update anomalies. Denormalize deliberately for read performance (precomputed counts, duplicated fields, materialized views) and accept the cost of keeping copies consistent.
Q46. Explain the types of joins and how databases execute them.
INNER, LEFT/RIGHT OUTER, FULL OUTER, CROSS, and self joins. Execution strategies: nested loop (good when one side is small and the other is indexed), hash join (build a hash table on the smaller side; good for large unsorted inputs), merge join (both sides sorted on the key).
Q47. What is a write-ahead log (WAL)?
Changes are appended to a sequential log and flushed before the corresponding data pages are written. After a crash, the database replays the log to recover committed work and roll back incomplete work. The same log often drives replication. SQLite explains its approach clearly in Atomic Commit In SQLite.
Q48. B-trees vs LSM-trees?
B-trees update pages in place, read fast, and are the default in most relational databases. LSM-trees (RocksDB, Cassandra) buffer writes in memory, flush sorted files, and merge them in the background (compaction): very high write throughput, with more read and space amplification managed by Bloom filters and compaction strategy.
Q49. What is MVCC?
Multi-version concurrency control keeps multiple versions of rows, so readers see a consistent snapshot without blocking writers, and writers don’t block readers. Old versions are cleaned up later (vacuum in PostgreSQL, purge in InnoDB).
Q50. SQL vs NoSQL?
Relational databases offer schemas, joins, transactions and a powerful query language; they fit most applications. NoSQL families trade some of that for specific strengths: document stores (flexible schema), key-value stores (simple, fast), wide-column stores (huge write volume, partitioned), graph databases (relationship traversal). Choose by access patterns, consistency needs and scale, not fashion.
Q51. Replication: synchronous vs asynchronous? Leader-follower vs multi-leader vs leaderless?
Synchronous replication waits for replicas before acknowledging a write (no data loss on failover, higher latency). Asynchronous acknowledges immediately (fast, but recent writes can be lost and replicas lag, causing stale reads). Leader-follower is the common default; multi-leader and leaderless (quorum-based, e.g. Dynamo-style) improve write availability but must resolve conflicts.
Q52. Sharding: how and what goes wrong?
Split data across nodes by a key, using range partitioning (good for range scans, risk of hot spots) or hash partitioning (even spread, no range scans). Problems: cross-shard queries and transactions, rebalancing, and hot keys (one celebrity user). Consistent hashing limits data movement when nodes change.
Q53. What is connection pooling and why does it matter?
Opening a database connection is expensive (TCP, TLS, auth, backend process). Pools reuse a bounded set of connections, protecting the database from too many concurrent connections; poolers like PgBouncer do this for PostgreSQL.
Q54. What is the N+1 query problem?
Loading a list of N items with one query, then running one query per item for related data. Fix with a join, a batched WHERE id IN (...), or the ORM’s eager loading.
Part 4: Concurrency
Q55. Concurrency vs parallelism?
Concurrency is structuring a program as independent tasks that can make progress in overlapping time periods. Parallelism is executing them at literally the same time on multiple cores. A single-core event loop is concurrent but not parallel.
Q56. What is a race condition? Give an example.
The outcome depends on the timing of threads. count += 1 is read, add, write; two threads can both read 5 and both write 6. Fix with a lock, an atomic operation, or by not sharing mutable state.
Q57. Mutex vs semaphore vs condition variable?
- Mutex: mutual exclusion; one owner at a time, released by the owner.
- Semaphore: a counter allowing up to N holders (a binary semaphore is like a mutex but without ownership). Good for limiting concurrent access to a pool.
- Condition variable: lets threads wait for a condition while releasing a lock, and be woken by
notify. Always wait in awhileloop because of spurious wakeups and competing consumers.
BoundedBuffer in the code shows a lock plus two condition variables solving producer-consumer.
Q58. What are the four conditions for deadlock, and how do you prevent it?
Mutual exclusion, hold and wait, no preemption, and circular wait (the Coffman conditions). Break any one: acquire locks in a global order (breaks circular wait, the most common fix), acquire all locks at once or use try_lock with backoff (breaks hold and wait), use timeouts. Avoidance algorithms like the banker’s algorithm grant requests only if the system stays in a safe state; bankers_safe() implements the safety check.
Q59. Deadlock vs livelock vs starvation?
Deadlock: threads wait for each other forever, doing nothing. Livelock: threads keep reacting to each other and changing state without progress (two people stepping aside in a corridor). Starvation: one thread never gets a resource because others keep winning (fix with fairness or aging).
Q60. What is a reader-writer lock?
Allows many concurrent readers or one writer. Good for read-heavy data, but naive versions starve writers; fair implementations queue writers.
Q61. What is a spinlock and when would you use one?
A lock where waiting threads loop checking it instead of sleeping. It avoids context switch costs when the critical section is very short and threads run on separate cores, which is why kernels use them; in user space it usually wastes CPU.
Q62. What are atomic operations and compare-and-swap?
CPU instructions that read-modify-write memory indivisibly. CAS sets a value only if it still equals an expected value, and is the building block of lock-free data structures. Watch out for the ABA problem (value changed and changed back), solved with version tags.
Q63. What is a memory model and why does volatile or atomic matter?
Compilers and CPUs reorder memory operations for speed. Without proper synchronization (locks, atomics with the right ordering), one thread may see another’s writes late or in a different order. Language memory models (Java, C++, Go, Rust) define what’s guaranteed; data races in C/C++ are undefined behavior.
Q64. Threads vs async/await?
Threads are scheduled preemptively by the OS and suit CPU-bound work and blocking libraries. Async tasks are cooperatively scheduled on an event loop and suit many concurrent I/O-bound operations with little memory per task, but one blocking call stalls the whole loop.
Q65. What is Python’s GIL and how is it changing?
In CPython the global interpreter lock allows only one thread to execute Python bytecode at a time, so threads help I/O-bound but not CPU-bound pure-Python work (use processes or native extensions). Python 3.13 introduced an experimental free-threaded build without the GIL, and Python 3.14 made the free-threaded build officially supported (still optional, not the default). Docs: threading, asyncio.
Q66. What is a thread pool and how do you size it?
A fixed set of worker threads pulling tasks from a queue, avoiding the cost of creating threads per task and bounding concurrency. For CPU-bound work, about the number of cores; for I/O-bound work, more, roughly cores x (1 + wait time / compute time), validated by measurement.
Q67. How would you implement a rate limiter?
A token bucket: tokens refill at a fixed rate up to a capacity; each request spends a token or is rejected. It allows short bursts while enforcing the average rate. Alternatives: leaky bucket (smooth output), fixed window counters (simple, bursty at boundaries), sliding window logs or counters (more accurate). TokenBucket in the code takes an injectable clock so it’s testable. Distributed versions keep counters in a shared store such as Redis.
Q68. Implement an LRU cache.
A hash map for O(1) lookup plus a doubly linked list ordered by recency: move a key to the front on access, evict from the back when full. In Python, OrderedDict provides both; LRUCache adds a lock for thread safety.
Part 5: Distributed Systems Basics
Q69. What is the CAP theorem?
During a network partition, a distributed data store must choose between consistency (every read sees the latest write) and availability (every request gets a non-error response). Without partitions you can have both. PACELC adds: else, choose between latency and consistency.
Q70. Strong vs eventual consistency?
Strong (linearizable): the system behaves as if there’s one copy and operations happen instantly at some point. Eventual: replicas converge if writes stop, but reads may be stale. In between: read-your-writes, monotonic reads, causal consistency. The Jepsen consistency map shows how models relate.
Q71. What is consensus and why do we need Raft or Paxos?
Getting a group of nodes to agree on values (like the order of log entries) despite failures, as long as a majority is up. Used for leader election and replicated state (etcd, ZooKeeper-like systems). Raft was designed to be understandable; its site has a visualization.
Q72. What is idempotency and why does it matter?
An operation that has the same effect if done once or many times. Networks force retries, so payment and order APIs use idempotency keys to make retries safe.
Q73. Exactly-once delivery?
Across a network, true exactly-once delivery isn’t achievable in general; systems achieve exactly-once processing with at-least-once delivery plus idempotent or transactional consumers (deduplicate by message ID).
Q74. Why are clocks a problem in distributed systems?
Physical clocks drift and can jump, so timestamps from different machines can’t reliably order events. Use logical clocks (Lamport clocks, vector clocks) for ordering, or bounded-uncertainty clocks in specialized systems.
Numbers Every Engineer Should Know
Orders of magnitude, popularized by Jeff Dean and widely shared (gist); modern hardware shifts some values, but the ratios are what matter:
| Operation | Rough time |
|---|---|
| L1 cache reference | ~1 ns |
| Branch mispredict | ~3-5 ns |
| Main memory reference | ~100 ns |
| Read 4 KB randomly from NVMe SSD | ~10-100 µs |
| Round trip within a data center | ~0.5 ms |
| Read 1 MB sequentially from SSD | ~0.1-1 ms |
| Disk (HDD) seek | ~5-10 ms |
| Round trip US East to Europe | ~70-100 ms |
Takeaways: memory is ~100x slower than cache, the network inside a data center is cheaper than a spinning-disk seek, and cross-continent round trips dominate user-facing latency.
Runnable Exercises
All in src/osnet.py, tested in tests/test_osnet.py:
| Function / class | Interview topic |
|---|---|
schedule(jobs, "fcfs" / "sjf" / "rr") |
CPU scheduling and waiting times |
page_faults(refs, frames, "fifo" / "lru" / "opt") |
Page replacement, Belady’s anomaly |
bankers_safe(...) |
Deadlock avoidance |
BoundedBuffer |
Producer-consumer with condition variables |
LRUCache |
O(1) cache with eviction, thread-safe |
TokenBucket |
Rate limiting |
subnet_info, same_subnet |
CIDR and subnetting |
Exercises to try yourself: add a preemptive SRTF policy, a clock (second-chance) page replacement policy, a reader-writer lock with writer preference, and a sliding-window rate limiter, each with tests.
Best Resources (Free and Paid)
Operating systems
| Resource | Cost | Notes |
|---|---|---|
| Operating Systems: Three Easy Pieces (OSTEP) by Remzi and Andrea Arpaci-Dusseau | Free online | Best single OS book for interviews |
| MIT 6.1810 Operating System Engineering | Free materials | Hands-on xv6 kernel labs |
| Linux man pages | Free | System calls and tools, authoritative |
| Computer Systems: A Programmer’s Perspective (site) | Paid book | Memory, linking, processes from the programmer’s view |
| Nand2Tetris | Free course | Build a computer from logic gates up |
Networking
| Resource | Cost | Notes |
|---|---|---|
| Computer Networks: A Systems Approach | Free online | Full textbook, open licensed |
| High Performance Browser Networking by Ilya Grigorik | Free online | TCP, TLS, HTTP/2, performance |
| Beej’s Guide to Network Programming | Free | Sockets in practice |
| The Internet explained from first principles | Free | Clear long-form explanation |
| RFCs: TCP 9293, QUIC 9000, HTTP/3 9114, TLS 1.3 8446 | Free | Primary sources |
| Computer Networking: A Top-Down Approach (Kurose and Ross) | Paid book | Standard university textbook |
Databases
| Resource | Cost | Notes |
|---|---|---|
| CMU 15-445/645 Database Systems and lecture videos | Free | Storage, indexes, transactions, recovery |
| Use The Index, Luke | Free online | Indexing for developers |
| PostgreSQL docs: transaction isolation | Free | Precise isolation behavior |
| Designing Data-Intensive Applications by Martin Kleppmann (site) | Paid book | The standard for storage, replication, consistency |
Concurrency and distributed systems
| Resource | Cost | Notes |
|---|---|---|
| The Little Book of Semaphores by Allen Downey | Free | Synchronization puzzles with solutions |
| Is Parallel Programming Hard, And, If So, What Can You Do About It? | Free | Deep dive, by a Linux RCU maintainer |
| Cambridge Concurrent and Distributed Systems notes | Free PDF | Clear lecture notes on distributed systems |
| Raft | Free | Paper, visualization, implementations |
| Jepsen consistency models | Free | Precise definitions |
Roadmaps
- Teach Yourself Computer Science - a curated path through all nine core CS subjects.
- The System Design Primer - applies these fundamentals to design interviews.
Best pick: OSTEP for operating systems and concurrency, High Performance Browser Networking for networking, CMU 15-445 lectures plus Use The Index, Luke for databases. All free.
FAQ
What CS fundamentals are asked in software engineering interviews? Process vs thread, memory and virtual memory, scheduling, deadlocks, TCP vs UDP, what happens when you type a URL, DNS, HTTP and TLS, database indexes, ACID and isolation levels, SQL vs NoSQL, race conditions and locks.
Do FAANG-style companies ask OS and networking questions? Often indirectly, through system design and debugging discussions, and directly for infrastructure, SRE, systems and new-grad roles.
What is the difference between a process and a thread? A process has its own address space and resources; threads run inside a process and share its memory, each with its own stack and registers.
What’s the difference between TCP and UDP? TCP is reliable, ordered and connection-oriented with flow and congestion control; UDP is connectionless and unreliable with minimal overhead.
What are database isolation levels? Read uncommitted, read committed, repeatable read and serializable, each preventing more anomalies (dirty reads, non-repeatable reads, phantoms, write skew) at more cost.
How do I prevent deadlocks? Acquire locks in a consistent global order, hold them briefly, use timeouts or try-locks, and avoid calling unknown code while holding a lock.
How long does it take to review CS fundamentals? About two weeks if you studied them before; four to six weeks from scratch using the roadmap above.
Where to Go Next
- system-design-case-studies and low-level-design-primer
- devops-interview-questions for production Linux and networking
- leetcode-patterns for the coding rounds
- salary-negotiation-guide after the offer
Contributing
- Fix mistakes, add questions with concise answers in your own words, or add exercises.
- Code must use only the Python standard library and come with a test; run
python3 -m unittest discover -s tests. - Cite primary sources (RFCs, official docs) for protocol details.
License
MIT. Copyright (c) 2026 Ralpberry Labs.
If this helped you, a star helps others find it.
More free resources
Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.