Scrivio Interview library

Distributed systems concepts

42 questions in 9 subtopics.

About this topic

Distributed systems concepts explain why software spread across many machines behaves differently from a single process. Networks delay and drop messages, nodes pause or fail partially, clocks disagree, and a caller often cannot tell whether a remote operation happened. Production incidents follow directly: duplicate payments after retries, two leaders after a network blip, locks that expire under a paused process, and clusters that flap or split in two. The questions cover failure models, clocks and logical ordering, consensus with Raft and Paxos, leader election and coordination services, distributed locks and fencing tokens, delivery semantics, idempotency and deduplication, gossip and failure detection, and the probabilistic structures that make large-scale systems efficient, combining how each mechanism works with realistic incidents, Java code and the decisions senior engineers and leaders make.

Partial failure and failure models

In a distributed system some parts fail while others keep running, and a timeout cannot reveal whether a remote node crashed, is slow, or lost the reply. Failure models such as crash-stop, crash-recovery, omission and Byzantine state what a design must survive. Understand gray failures that pass health checks, how slowdowns turn into self-sustaining outages, and how to test systems under realistic faults.

ConceptFoundations6 min read

In a distributed system parts can fail while the rest keeps running, and a node cannot see directly whether another node has crashed, is slow or is unreachable. Failure models name the kinds of faults a design is expected to survive.

Describe the crash-stop, crash-recovery, omission and Byzantine failure models, and explain why a timeout on a remote call cannot tell you which of them happened.
DebuggingIntermediate6 min read

A search service fans each query out to 40 index nodes and waits for all of them. Health checks pass everywhere, but fleet p99 latency rose from 120 ms to 900 ms. One node has a faulty network card that drops 3 percent of packets, so many of its responses wait for TCP retransmission.

Why do health checks miss this kind of failure, why does one degraded node set the latency of the whole fleet, and how would you detect and contain it?
DesignAdvanced6 min read

A team has built a replicated metadata service in Java on top of a consensus library. It passes unit and integration tests, but it has never been tested under network partitions, clock jumps, process pauses or disk faults.

Design a fault-injection test programme that would give you confidence in its correctness: which faults to inject, how to inject them, and what to check.
LeadershipPrincipal6 min read

A review of last year's major outages finds that few began with a clean crash. Most started with a slowdown, such as a slow dependency or one degraded zone, after which retries, cache misses and growing queues kept the system down even after the trigger had gone.

As the senior technical leader, how do you explain this pattern to the organisation, and which standards and investments do you put in place?

Clocks and ordering

Machines keep their own clocks, synchronised only approximately, and corrections can make time jump. Ordering events across machines by wall-clock time is therefore unreliable. Understand monotonic versus time-of-day clocks, Lamport and vector clocks for causal order, hybrid logical clocks, and how databases that depend on bounded clock uncertainty turn clock errors into waiting, retries or shutdowns.

ConceptFoundations6 min read

Every server has a time-of-day clock synchronised by NTP or a similar service and a monotonic clock that only moves forward. Distributed systems often need to order events that happened on different machines.

Can you order events from two servers by their wall-clock timestamps? Explain what clock synchronisation can and cannot guarantee, and when each kind of clock should be used.
ConceptFoundations6 min read

Logical clocks order events by cause and effect rather than by physical time. Lamport clocks and vector clocks are the two classic designs.

How do Lamport clocks and vector clocks work, and what can each of them tell you about two events?
CodingIntermediate6 min read

A hybrid logical clock (HLC) combines physical time with a logical counter, so timestamps stay close to wall-clock time while still respecting causality between nodes. Several distributed databases use one.

Implement an HLC in Java with now() for local and send events and update(remote) for receive events, and explain how it behaves when the local physical clock is behind.
DebuggingIntermediate7 min read

Services write cache entries with an absolute expiry time taken from their own clocks. After maintenance, entries written by pods on one node expire at once on other pods, and session tokens issued on that node are rejected elsewhere as expired. chronyc there shows the clock 94 seconds slow.

Explain how one node's clock caused both symptoms, how you would fix the immediate problem, and how you would make the system tolerate clock errors.
InternalsAdvanced7 min read

Globally distributed databases must order transactions across continents without a single shared clock. One well-known design uses atomic clocks and GPS with explicit uncertainty intervals; others use hybrid logical clocks with a configured maximum clock offset.

How does commit wait with bounded clock uncertainty give externally consistent transactions, how does the hybrid-clock approach differ, and what does each require from your clock infrastructure?

Consensus with Raft and Paxos

Consensus protocols let a group of nodes agree on an ordered log despite crashes and delays, as long as a majority is available. Raft and Paxos underpin etcd, ZooKeeper, KRaft and distributed SQL. Understand majority quorums and failure tolerance, how Raft elects leaders and commits entries, why disk and network latency cause leadership churn, and how placement across sites decides availability.

ConceptFoundations7 min read

Consensus lets a group of nodes agree on a sequence of values, such as log entries or the current leader, even when some nodes crash or messages are delayed. It underlies etcd, ZooKeeper, KRaft and distributed SQL databases.

What problem does consensus solve, why does it need a majority quorum, how many failures can clusters of 3, 4 and 5 nodes survive, and how do Raft and Paxos relate?
InternalsIntermediate7 min read

Raft divides time into terms, each with at most one leader. The leader appends client commands to its log and replicates them to followers with AppendEntries messages.

Walk through how a Raft leader is elected, how entries are replicated and committed, and why a new leader cannot commit an entry from an earlier term simply by counting replicas.
DebuggingIntermediate6 min read

A Kubernetes control plane runs a three-member etcd cluster on VMs with network-attached disks. During busy periods the API server logs 'etcdserver: request timed out', etcd warns that apply requests took too long, and the leader changes about 30 times an hour.

What is the likely cause, which etcd metrics confirm it, and how do you fix it?
DesignAdvanced7 min read

A five-node consensus cluster for a payments metadata service runs three nodes in data center A and two in data center B. When data center A lost power for 40 minutes, the nodes in B could not elect a leader and all writes stopped.

Explain why B could not continue, and design a placement and failover approach that survives the loss of either data center.
LeadershipPrincipal6 min read

A team wants to build a new internal metadata service that needs strongly consistent replication. They propose writing their own consensus implementation in Java because existing options look heavy.

As the senior technical leader, how do you weigh building consensus in-house against embedding a library or using an existing coordination service, and which conditions would you set?

Leader election and coordination services

Many systems need exactly one active instance for a task, chosen automatically when the current one fails. Coordination services such as ZooKeeper and etcd, Kubernetes Leases and database locks provide election through sessions, leases and watches. Understand the election recipes, why a former leader can keep acting after losing leadership, and how shared coordination services become a source of cascading failures.

InternalsFoundations7 min read

ZooKeeper and etcd are coordination services: small, strongly consistent stores with sessions or leases and change notifications, often used to elect one leader among many instances.

How does leader election work with ZooKeeper ephemeral sequential znodes, why does each candidate watch only its predecessor, and how does the etcd approach with leases compare?
CodingFoundations6 min read

A Spring Boot service runs on six pods, and one background task, rebuilding a daily report index, must run on exactly one pod at a time while the other pods stand by.

Show how to elect a leader with Spring Integration's LockRegistryLeaderInitiator backed by a JdbcLockRegistry, how the task starts and stops on leadership events, and what happens when the leader pod hangs.
DebuggingIntermediate7 min read

A Kubernetes controller written in Java uses Lease-based leader election with leaseDuration 15 s, renewDeadline 10 s and retryPeriod 2 s. After a network blip on one node, logs show two replicas both reconciling resources for about 20 seconds, which created duplicate cloud load balancers.

How could two replicas act as leader at the same time, and what changes in code and configuration stop this from causing harm again?
ScenarioAdvanced6 min read

A five-server ZooKeeper ensemble serves 60 services for configuration, discovery and leader election, with 1.2 million watches. After a 6-second GC pause on its leader, thousands of clients logged 'Session expired' and re-registered at once, and the ensemble stayed overloaded for 25 minutes.

Explain the cascade, how you would stabilise the ensemble, and how you would change the way services use it.
LeadershipPrincipal6 min read

Your company runs several self-managed ZooKeeper ensembles, mostly for older Kafka clusters, plus leader election in two Java services and some configuration. Kafka 4.x no longer uses ZooKeeper, and new services mostly run on Kubernetes.

As the senior technical leader, what coordination strategy do you set for the next five years, and how do you retire or keep ZooKeeper?

Distributed locks and fencing

A distributed lock gives one process exclusive access across machines, but a holder can pause, lose its lease and still act. Locks that only prevent duplicate work tolerate this; locks that protect data need fencing tokens checked by the resource, or a design that needs no lock. Understand the difference, how to build a lease with a fencing token, and what happens when the lock service itself fails.

ConceptFoundations6 min read

Teams use distributed locks for very different reasons. Some locks only avoid doing work twice, while others protect data from corruption, and the difference decides what kind of lock is good enough.

Classify these uses as efficiency or correctness locks and say what each needs: a nightly report generator, rebuilding a cache entry after a miss, charging a customer's card for an order, and appending to a shared file in object storage.
CodingIntermediate7 min read

A job coordinator must make sure that only the current lease holder updates a table of work assignments. The team wants to use the PostgreSQL database they already run rather than add Redis or ZooKeeper.

Write the SQL and outline the Java code for a lease with a fencing token in PostgreSQL: acquire, renew, release, and a guarded update that rejects a stale holder.
DebuggingIntermediate7 min read

Account updates in a payments service are wrapped in a Redisson lock named after the account id. At 3,000 requests per second, p99 latency has reached 2 seconds, logs fill with failures to acquire the lock within the 500 ms wait time, and a few accounts receive most of the traffic.

Why has the lock become the bottleneck, and how would you redesign account updates so correctness does not depend on a distributed lock?
LeadershipPrincipal6 min read

The Redis cluster used for distributed locks by 30 services was unavailable for 50 minutes. Some services stopped processing entirely, while others ignored the failure, ran their jobs on every pod and sent duplicate invoices.

As the senior technical leader, what policy do you set for how services behave when their lock or coordination backend is down, and how do you roll it out?

Delivery semantics

Messaging and integration guarantees are at-most-once, at-least-once or effectively exactly-once, and the real guarantee depends on when work is acknowledged relative to its side effects. Understand how acknowledgement placement works in Kafka, RabbitMQ and SQS, why exactly-once holds only inside closed systems, where duplicates and silent losses creep into pipelines, and how webhooks and notifications should be delivered.

ConceptFoundations7 min read

Messaging systems describe delivery as at-most-once, at-least-once or exactly-once. The guarantee a consumer really gets depends mostly on when it acknowledges a message relative to doing the work.

Explain the three semantics, and show where the acknowledgement must happen to get at-most-once or at-least-once with a Kafka consumer, a RabbitMQ consumer and an SQS consumer.
DebuggingIntermediate6 min read

A notification service consumes OrderShipped events from Kafka with Spring Kafka and sends an email through an external provider for each one. After every deployment some customers receive the same email two or three times, and the provider offers no idempotency key.

Explain where the duplicates come from and how you would reduce them to nearly zero.
DesignIntermediate7 min read

Your platform sends webhooks to 3,000 partner endpoints for order events. Partners complain about events missed during their outages, duplicates after your retries, and events that arrive out of order.

Design webhook delivery: the guarantee you offer, the retry schedule, ordering, and what you require from partners.
ScenarioAdvanced6 min read

A finance reconciliation finds that about 0.02 percent of payment events produced by 30 services never reach the warehouse. Events flow from the services through Kafka and a stream processor to a warehouse loader, and every team believes its part is at-least-once.

How do you find where at-most-once behaviour crept in, and which controls do you add so that losses are detected within minutes?

Idempotency and deduplication

Because retries and redeliveries are unavoidable, operations must be safe to repeat. Idempotency keys, natural idempotency and deduplication stores each cover different scopes and time windows. Understand what producer and broker deduplication do and do not cover, why keys must identify operations rather than attempts, where deduplication state must live, and how to integrate safely with systems that are not idempotent.

ConceptFoundations7 min read

Deduplication mechanisms differ in what they compare and how long they remember. A producer-level dedup, a broker-level deduplication window and an application idempotency table each cover a different part of the path.

Compare the Kafka idempotent producer, SQS FIFO deduplication and an application idempotency-key table: which duplicates each removes, over what scope and time window, and what each leaves to you.
DebuggingIntermediate6 min read

A Java consumer service deduplicates device events by event id, keeping for each assigned partition an in-memory map of ids seen in the last 10 minutes. After the topic grew from 12 to 24 partitions the duplicate rate rose from zero to 0.4 percent, and it also spikes after every deploy.

Explain both effects and how you would redesign the deduplication.
ScenarioIntermediate6 min read

A payments API keeps idempotency keys for 24 hours, yet about 40 duplicate charges happen a week. Three patterns appear: the mobile app makes a new key when it restarts, the gateway retries with a key it generates itself, and a dead-letter replay three days later charged again.

Explain why each pattern defeats the idempotency table and how you would fix them.
DesignAdvanced7 min read

An order workflow calls a legacy shipping partner's SOAP API to create shipments. The API accepts no idempotency key and timeouts are common. Last month, retries after timeouts created 230 duplicate shipments.

Design the integration so that retries are safe even though the partner API is not idempotent.

Gossip, membership and failure detection

Large clusters track which members are alive by gossiping state between random peers and by detecting failures from missed heartbeats. Detection is always a trade between speed and false alarms. Understand gossip convergence, phi accrual and SWIM-style detectors, why CPU throttling and pauses cause flapping, and how clusters avoid splitting into two independent halves during a network partition.

ConceptFoundations6 min read

Gossip protocols spread information the way rumours spread: each node regularly exchanges state with a few randomly chosen peers. Cassandra, Consul and Redis Cluster use gossip for membership and cluster state.

How does a gossip protocol work, how fast does information reach every node, and what are its strengths and weaknesses compared with a central registry?
ConceptFoundations6 min read

A failure detector decides when a node should be treated as dead. Most systems use heartbeats with timeouts, and some use adaptive detectors such as the phi accrual failure detector.

What trade-off does a heartbeat timeout make, and how does the phi accrual failure detector improve on a fixed timeout?
InternalsIntermediate6 min read

SWIM is a membership protocol designed for large clusters. It separates failure detection from the spreading of membership updates, and it is the basis of the memberlist library that Consul and Serf use.

Describe SWIM's probing with indirect pings, its suspicion mechanism with incarnation numbers, and how updates spread. Why does it scale better than all-to-all heartbeats?
DebuggingIntermediate6 min read

A Cassandra cluster on Kubernetes logs lines such as 'InetAddress /10.2.14.7 is now DOWN' followed seconds later by 'is now UP', many times an hour. During each flap, client requests for that node's ranges time out. The pods have CPU limits and show heavy CFS throttling.

Explain why healthy nodes are being marked down, and what you would change in the platform and in the database settings.
ScenarioAdvanced7 min read

A Java service keeps session state in an embedded in-memory data grid whose 10 nodes form a cluster through gossip-style membership. A network partition split them 6 and 4; each side declared the other dead and kept writing, and after healing the grid held two versions of many sessions.

Explain why both sides kept running, which split-brain resolution strategies exist, and how you would configure and test the cluster.
LeadershipPrincipal5 min read

Several teams build stateful Java services that form their own clusters with embedded data grids or actor clusters to keep data in memory, while the platform standard is stateless services backed by external stores. Each cluster has its own membership and split-brain behaviour.

As the senior technical leader, when would you allow application-level clustering, and what would you require from teams that use it?

Bloom filters, Merkle trees and sketches

Probabilistic and hash-based structures let distributed systems answer questions about huge data sets with little memory or network traffic. Bloom filters rule out absent keys, Merkle trees locate differences between replicas, and sketches such as Count-Min estimate frequencies and merge across nodes. Understand how each works, its error bounds and sizing, and where storage engines and migrations rely on them.

ConceptFoundations7 min read

A Merkle tree is a tree of hashes: each leaf holds the hash of a block of data and each inner node holds the hash of its children. Replicated stores, Git and certificate transparency logs use Merkle trees to compare or verify large data sets cheaply.

How do two replicas use Merkle trees to find which parts of their data differ, and how many hashes must they exchange compared with sending everything?
CodingFoundations7 min read

A Bloom filter answers 'definitely not present' or 'possibly present' for set membership, using a bit array and several hash functions and far less memory than storing the keys themselves.

Implement a Bloom filter in Java for String keys, sized for n expected items and a target false-positive rate p, and explain how the number of bits and hash functions are chosen.
InternalsIntermediate7 min read

A Count-Min Sketch estimates how often items occur in a stream using a small, fixed amount of memory. It is used for heavy-hitter detection, per-key rate limiting and cache admission policies.

How does a Count-Min Sketch work, why does it only ever overestimate, how do its width and depth set the error, and how do you combine sketches computed on 50 pods?
DebuggingIntermediate7 min read

Read latency on a Cassandra table rose from 3 ms to 25 ms over a month. nodetool tablehistograms shows reads touching a median of 9 SSTables, and nodetool tablestats reports a Bloom filter false ratio of 0.28 for the table, whose bloom_filter_fp_chance is 0.1.

Explain how Bloom filters are used on the read path of an LSM storage engine, why they are not helping here, and what you would change.
DesignAdvanced7 min read

A team is migrating 2 billion rows of account history from sharded MySQL to a new distributed database while both stay live, with change data capture keeping the target in sync. Leadership wants proof the copies match before cutover, and a row-by-row comparison would take days.

Design a verification method based on hash trees that finds differences quickly, copes with rows changing during the check, and tells you exactly what to repair.