Integration / Event Ordering in Distributed Systems Interview questions
Last updated
1. What is event ordering in distributed systems?
Event ordering is the problem of deciding which of two events happened first, or whether the order even matters, when the events occur on different machines that share no global clock.
On a single machine the CPU clock gives every event a clear position in time. Across nodes, each one has its own clock and messages take unpredictable time to arrive, so "first" has to be defined rather than observed.
Systems use three broad approaches:
- Physical time - synchronized wall clocks such as NTP or TrueTime.
- Logical time - counters that capture cause and effect (Lamport and vector clocks).
- Agreement - a leader, sequencer or consensus log that simply decides the order.
Getting this wrong leads to lost updates, stale reads and replicas that diverge.
Take quiz
every event is processed by the same CPU
events never depend on each other
nodes have no shared global clock and messages have variable delay
network messages always arrive in sending order
Logical clocks
Synchronized physical clocks
A consensus-based log
Sorting events alphabetically by node name
2. Why is ordering events hard in distributed systems?
Ordering is hard because nodes disagree about time and the network gives no timing guarantees. Two machines can stamp events with clocks that differ by milliseconds or more, so comparing timestamps can give the wrong answer.
The main obstacles are:
- Clock drift - quartz oscillators run slightly fast or slow, typically tens of ppm.
- Variable latency - a message sent earlier can arrive later than one sent after it.
- Partial failure - a node may be slow or partitioned, not just dead, so you cannot tell what it has seen.
- No shared memory - there is no single counter everyone can read atomically.
Because of this, you can only prove an order when there is a causal path (a message chain) between two events. Everything else is either concurrent or needs extra coordination to order.
Take quiz
The sender's clock is always wrong
TCP reorders every packet on purpose
Messages are sorted by size before delivery
Network latency is variable and paths can differ
there is a causal path of messages or local steps between them
they have the same event type
their wall-clock timestamps differ by any amount
they ran on the same data center
3. What is the happened-before relation?
The happened-before relation (written a → b) was defined by Leslie Lamport in 1978. It is a partial order that says event a could have influenced event b.
It is built from three rules:
- If a and b are on the same process and a comes first, then
a → b. - If a is the sending of a message and b is its receipt, then
a → b. - If
a → bandb → c, thena → c(transitivity).
If neither a → b nor b → a holds, the events are concurrent. Concurrent does not mean simultaneous, only that neither could have affected the other.
Take quiz
a happened-before b
b happened-before a
they are concurrent
the relation is undefined
total order based on wall clocks
partial order based on causality
order based on message size
random ordering
4. What are concurrent events?
Two events are concurrent when neither can causally influence the other, that is, no chain of local steps and messages connects them in either direction.
Example: node A writes x=1 while node B writes x=2, and neither has yet received the other's update. Real-time order may exist, but the system has no way to know it, so the writes are concurrent.
Concurrency matters because it is exactly where conflicts happen. A system must either pick an order (last-write-wins, a sequencer), keep both versions (siblings), or merge them (CRDTs).
Vector clocks are the standard tool for detecting concurrency, since Lamport clocks cannot tell concurrent from ordered events.
Take quiz
are always identical writes
have no causal path between them in either direction
occur at exactly the same nanosecond
always run on different continents
A single wall-clock timestamp
Lamport clocks
Vector clocks
NTP offsets
5. What is a logical clock?
A logical clock is a counter-based mechanism that orders events by causality instead of real time. It does not measure seconds, it only guarantees that if one event can influence another, it gets a smaller timestamp.
Each process keeps its own counter and updates it on local events and message exchange. The counter values travel inside messages, which is how causal information spreads.
| Logical clock type | What it captures |
| Lamport clock | One integer; consistent with causality but cannot detect concurrency. |
| Vector clock | One counter per node; exactly characterizes causality and concurrency. |
| Hybrid logical clock | Physical time plus a logical counter; stays close to wall time. |
Take quiz
network bandwidth
the exact wall-clock time in UTC
the causal order of events
CPU temperature
Atomic clock
Lamport clock
NTP clock
Vector clock
6. What is a Lamport clock?
A Lamport clock is a single integer counter per process that gives a timestamp to every event so that causally related events are numbered in increasing order.
The rules are simple:
- Before each local event or send, increment the counter:
C = C + 1. - Attach
Cto every outgoing message. - On receive, set
C = max(C, msg.C) + 1.
class Lamport: def __init__(self): self.c = 0 def tick(self): self.c += 1; return self.c def recv(self, ts): self.c = max(self.c, ts) + 1; return self.c
It guarantees a → b implies C(a) < C(b). The reverse is not true, so a smaller timestamp does not prove causality.
Take quiz
always 0
local + ts
ts - 1
max(local, ts) + 1
a might have happened before b, but they may also be concurrent
a definitely caused b
a and b ran on the same node
b definitely caused a
7. What is a vector clock?
A vector clock is an array of counters, one slot per process, that records how many events each process is known to have seen. It captures causality exactly, including concurrency.
Update rules for process i:
- On a local event or send, increment its own slot:
V[i]++. - Send the full vector with the message.
- On receive, take the element-wise maximum, then increment
V[i].
Comparison: V(a) ≤ V(b) in every slot and different somewhere means a → b. If neither vector dominates the other, the events are concurrent.
The cost is size. The vector grows with the number of participants, which is why large systems prune or use variants such as dotted version vectors.
Take quiz
concurrent
identical
b happened before a
a happened before b
they only work on a single machine
metadata size grows with the number of nodes
they need atomic clocks
they cannot detect causality
8. What is clock drift?
Clock drift is the gradual divergence of a machine's clock from true time because its oscillator does not tick at exactly the nominal rate. Cheap quartz hardware typically drifts around 10-200 ppm, which can add up to several seconds per day if left uncorrected.
Temperature, voltage and hardware age all affect the rate. Virtual machines make it worse because the hypervisor may pause or throttle guests.
Services such as NTP or chrony periodically measure the offset against a reference and slew (slightly speed up or slow down) the clock, or step it if the error is large.
Drift is one of the main reasons raw timestamps from different nodes cannot be trusted to order events.
Take quiz
too many network hops
oscillators ticking slightly faster or slower than ideal
small message payloads
database indexes
encrypting timestamps
deleting old log files
adjusting (slewing or stepping) the local clock against a reference
sending vector clocks
9. What is clock skew?
Clock skew is the difference between the readings of two clocks at the same instant. Drift is the rate of error, while skew is the current gap between machines.
Suppose server A shows 10:00:00.000 and server B shows 10:00:00.350. The skew is 350 ms. If A logs an event at its 10:00:00.100 and B logs another at its 10:00:00.200 a moment later, B's timestamp looks later although it may actually have happened first.
Typical effects include out-of-order log lines, expired tokens that seem to be from the future, certificate validation failures, and wrong last-write-wins results.
Take quiz
the delay of one network packet
the rate at which a clock slows down
the difference between two clocks at the same moment
the number of events per second
smaller log files
more CPU cores
faster disk writes
wrong ordering when comparing their timestamps
10. What is NTP and how accurate is it?
NTP (Network Time Protocol) synchronizes machine clocks over a network by exchanging timestamped packets with time servers arranged in strata. Stratum 0 devices are atomic or GPS clocks, stratum 1 servers connect directly to them.
The client records four timestamps per exchange and computes the round-trip delay and clock offset. It filters several samples and gradually adjusts its clock.
| Environment | Typical accuracy |
| Public internet | Several to tens of milliseconds |
| Well-run LAN | Around 1 ms or better |
| PTP with hardware timestamps | Sub-microsecond |
Because the error is never zero and can spike when routes change, NTP is good for logs and coarse coordination but not for deciding the exact order of close events.
Take quiz
several hours
exactly zero
picoseconds
milliseconds to tens of milliseconds
Residual error means nearby events can appear in the wrong order
It encrypts all timestamps
It only works with vector clocks
It cannot run on Linux
11. What are the types of event ordering in distributed systems?
The usual types, from weakest to strongest, are:
| Ordering | Guarantee |
| FIFO | Messages from one sender are delivered in the order sent. |
| Causal | If one message could have caused another, everyone delivers them in that order. |
| Total | Every node delivers all messages in the same order, whether related or not. |
| Real-time (linearizable) | Order respects actual wall-clock order of completed operations. |
Stronger ordering costs more: extra messages, higher latency, and lower availability under partitions. Pick the weakest one your application can tolerate.
Take quiz
Total ordering
FIFO ordering
Random ordering
No ordering
all messages across all senders
messages from the same sender
messages sorted by size
only concurrent messages
12. What is the difference between total order and partial order?
In a total order every pair of events is comparable: one is before the other. In a partial order some pairs are incomparable, meaning concurrent.
| Partial order | Total order |
| Based on causality (happened-before). | Based on an agreed sequence for everyone. |
| Concurrent events stay unordered. | Concurrent events are forced into some order. |
| Cheap, no coordination. | Needs a sequencer, tie-breaking or consensus. |
| Example: vector clocks, causal broadcast. | Example: Raft log, Kafka partition, atomic broadcast. |
Lamport timestamps with a node-ID tie-breaker turn the partial order into a total order, but that order is arbitrary for concurrent events. It is consistent, not necessarily "true".
Take quiz
impossible
left unordered relative to each other
always ordered by wall clock
deleted
Happened-before alone
Local counters only
A replicated consensus log
Vector clock comparison
13. What is causal ordering?
Causal ordering guarantees that if message m1 causally precedes m2, every node delivers m1 before m2. Concurrent messages may be delivered in different orders on different nodes.
Classic example: Alice posts a question, Bob replies. A third user must never see Bob's reply before Alice's question. Without causal delivery, a slow link to the third node can produce exactly that.
Implementation usually attaches vector clocks (or dependency lists) to messages and holds back any message whose dependencies have not yet been delivered.
Causal order is the strongest model that remains available during network partitions, which is why causal consistency is popular in geo-replicated stores.
Take quiz
Having more than one node
Seeing two unrelated posts in different orders
Seeing a reply before the message it replies to
Using TCP
must be delivered by timestamp
are dropped
must be delivered identically everywhere
may be delivered in different orders at different nodes
14. What is FIFO ordering?
FIFO (first-in, first-out) ordering guarantees that messages sent by one process to a destination are delivered in the same order they were sent. It says nothing about the relative order of messages from different senders.
It is typically implemented with per-sender sequence numbers. The receiver buffers any message with a gap and delivers only the next expected number. TCP does this for a single connection.
FIFO is the weakest of the common orderings. For example, if A sends a1, a2 and B sends b1, one node may see a1 b1 a2 and another b1 a1 a2, and both are valid FIFO deliveries.
Take quiz
vector clocks only
a global atomic clock
random identifiers
per-sender sequence numbers
the relative order of messages from different senders
sequence numbers
messages from the same sender
delivery of message 1 before 2 from one sender
15. What are Snowflake IDs and how do they help ordering?
Snowflake IDs are 64-bit identifiers that embed a timestamp in the high bits, so IDs are roughly time-sortable (k-sortable) and can be generated on many nodes without coordination.
The classic Twitter layout is:
| Bits | Field |
| 41 | Milliseconds since a custom epoch |
| 10 | Worker / datacenter ID |
| 12 | Per-millisecond sequence |
Sorting by ID gives approximate creation order. Two IDs from different workers in the same millisecond have no true order, and clock skew or a backwards clock step can break monotonicity, so the generator must handle that case explicitly.
ULIDs and UUIDv7 follow the same idea with different layouts.
Take quiz
a millisecond timestamp
a random color
the user's password hash
the payload size
are always identical
have no guaranteed true order
always follow causality
are encrypted
16. How do you break ties in Lamport timestamps to get a total order?
Lamport timestamps can be equal for events on different nodes, so you append a unique node ID and compare the pair (counter, nodeId) lexicographically.
Rule: (c1, n1) < (c2, n2) if c1 < c2, or c1 == c2 and n1 < n2.
This gives every event a distinct position, so all nodes that see the same set of events will sort them identically. Lamport used this in his mutual exclusion algorithm, where requests are served in timestamp order.
The tie-break is arbitrary. It does not mean the lower node ID happened first, only that everyone agrees on the same answer.
Take quiz
the current wall-clock time
the unique node ID
the message size
a random number chosen at each node
Yes, if NTP is running
Yes, always
No, it is only a consistent arbitrary choice
Only on weekdays
17. How do vector clocks detect concurrent updates?
You compare two vectors slot by slot. If one is greater than or equal in every slot, it descends from the other. If each is greater in at least one slot, neither knows about the other's update, so the updates are concurrent.
def compare(a, b): ge = all(x >= y for x, y in zip(a, b)) le = all(x <= y for x, y in zip(a, b)) if ge and le: return 'equal' if le: return 'a before b' if ge: return 'b before a' return 'concurrent'
Example: [2,1] vs [1,2]. The first slot says A is ahead, the second says B is ahead, so neither dominates and they are concurrent.
Once concurrency is detected, the application can keep both versions or merge them.
Take quiz
they are unrelated
the second happened after the first
the first descends from the second
they are concurrent
ordered by the larger sum
equal
invalid
concurrent
18. What is the difference between Lamport clocks and vector clocks?
Both are logical clocks, but they differ in how much causal information they keep.
| Aspect | Lamport clock | Vector clock |
| State per process | One integer | One integer per process |
| Message overhead | Constant | Grows with N |
a→b implies smaller timestamp |
Yes | Yes |
Smaller timestamp implies a→b |
No | Yes |
| Detects concurrency | No | Yes |
| Typical use | Total ordering, mutual exclusion | Conflict detection, causal delivery |
Choose Lamport when you only need a consistent ordering. Choose vector clocks when you must know whether two updates conflict.
Take quiz
Lamport clock
Neither
Both, equally
Vector clock
Constant-size metadata per message
No counters needed
Detect concurrency
Exact causality
19. What is the difference between physical and logical clocks?
A physical clock measures real elapsed time and must be synchronized to be comparable across machines. A logical clock only counts events and is concerned with causality, not seconds.
| Physical clock | Logical clock |
| Measures real time (UTC). | Counts events; no relation to real time. |
| Subject to drift and skew. | Immune to drift. |
| Useful for TTLs, logs, human-readable times. | Useful for ordering and conflict detection. |
| Can order events only within sync error. | Orders causally related events exactly (vector) or consistently (Lamport). |
| Examples: NTP, GPS, TrueTime. | Examples: Lamport, vector, version vectors. |
Hybrid logical clocks combine the two to get readable timestamps with causal guarantees.
Take quiz
clock drift
causality
counters
message passing
Vector clock
GPS-disciplined clock
Version vector
Lamport counter
20. Why can't we rely on wall-clock timestamps for ordering?
Because wall clocks on different machines are never perfectly aligned, and two events closer together than the sync error cannot be ordered reliably.
- Skew makes a later event on a slow clock look earlier.
- Clock steps from NTP corrections or leap seconds can make time go backwards.
- VM pauses and live migration freeze clocks.
- Last-write-wins on timestamps can silently discard the newer write.
A known real-world case: Cassandra's default timestamp-based conflict resolution can drop writes when the node clocks disagree. That is why operators insist on tight NTP or chrony and why some systems use logical or hybrid clocks instead.
Use wall time for display and expiry, not as the source of truth for order, unless you have bounded uncertainty like TrueTime.
Take quiz
faster network speed
a later event to receive a smaller timestamp
guaranteed causal order
more disk space
resolving all conflicts safely
proving causality
display and expiry checks
replacing consensus
21. What are hybrid logical clocks?
A hybrid logical clock (HLC) combines a physical timestamp with a small logical counter. The result stays close to real time but still respects causality, even when physical clocks are a bit off.
Each timestamp is (l, c), where l is the highest physical time seen and c breaks ties:
- On a local event:
l' = max(l, now). Ifl'equals the oldl, incrementc, otherwise resetcto 0. - On receive: take the max of local
l, messagelandnow, then adjustcto be larger than any equal value seen.
HLCs are used by CockroachDB and MongoDB. They fit in 64-96 bits, unlike vector clocks, and timestamps remain human-readable.
Take quiz
two random numbers
an IP address and a port
physical time and a logical counter
a vector and a hash
it never uses physical time
it needs atomic clocks
it detects concurrency perfectly
constant size and readable time
22. How does Google Spanner's TrueTime order events?
TrueTime exposes time as an interval [earliest, latest] instead of a single value, so the API admits the uncertainty. Google keeps it small (a few milliseconds) with GPS receivers and atomic clocks in each datacenter.
Spanner assigns each transaction a commit timestamp that lies inside this interval, then waits until the timestamp is definitely in the past on all clocks (commit wait) before releasing results.
That guarantees external consistency: if transaction T1 finishes before T2 starts, T1's timestamp is smaller than T2's, so timestamp order matches real-time order across the globe.
The trade-off is a small added commit latency equal to the uncertainty window.
Take quiz
a vector
only a counter
a single exact value
an uncertainty interval
waiting out the uncertainty before committing
using only Lamport clocks
ignoring clocks
skipping replication
23. What is commit wait in Spanner?
Commit wait is a deliberate pause in which a transaction coordinator holds back acknowledging a commit until the chosen commit timestamp s is certainly in the past, i.e. TT.after(s) returns true.
Why it works: after the wait, any transaction that starts later will receive a timestamp greater than s, even if its node's clock is slightly off, because the uncertainty has been covered.
The wait is roughly twice the clock error bound, typically around 7 ms. Spanner overlaps it with the Paxos replication of the commit, so much of it is hidden.
Shrinking the uncertainty bound directly shrinks commit latency, which is why Google invested in atomic clocks.
Take quiz
the commit timestamp is definitely in the past
a vector clock reaches zero
all data is deleted
the next day
SQL syntax
commit latency
disk capacity
vector clock size
24. What is a version vector and how does it differ from a vector clock?
A version vector tracks the versions of replicas of a data item, while a vector clock tracks the events of processes in a computation.
| Version vector | Vector clock |
| One entry per replica that updated the object. | One entry per process; incremented on every event. |
| Incremented only on update to data. | Incremented on send, receive, local events. |
| Used for replica conflict detection (Dynamo, Riak). | Used for causal delivery and general ordering. |
Because only updates count, version vectors stay smaller and are enough for storage systems that just need to know whether one replica's value descends from another's.
Take quiz
encrypt messages
detect conflicts between replicas of data
measure CPU time
order TCP packets
each SQL read
every network packet
data updates by a replica
every clock tick
25. How does Dynamo-style conflict resolution use vector clocks?
In Dynamo, each write carries a vector clock context from the previous read. The coordinator increments its own entry and stores the new value with that clock.
On a read, replicas may return different versions:
- If one clock descends from the others, the old versions are discarded (syntactic reconciliation).
- If clocks are concurrent, all versions are returned as siblings and the client merges them, then writes back the merged value.
Example: a shopping cart modified on two replicas during a partition returns two carts, and the application unions them. Nothing is silently lost, but the application must handle merging. Clock size is bounded by truncating the oldest entries.
Take quiz
checkpoints
replicas
siblings
parents
The load balancer
The disk controller
NTP
The client application merges them
26. What is last-write-wins and why is it risky?
Last-write-wins (LWW) resolves conflicts by keeping the value with the highest timestamp and discarding the rest. It is simple and needs no coordination.
The risks come from the timestamp:
- Skewed clocks can make an older write win.
- Concurrent writes are dropped silently, even when both mattered.
- Concurrent increments or list appends lose data.
Example: two users add different items to the same cart object on two replicas. With LWW only one cart survives.
LWW is acceptable for idempotent, whole-value overwrites such as a profile photo URL, and risky for counters, sets and anything that must merge. Alternatives are vector clocks with siblings, or CRDTs.
Take quiz
the node name alphabetically
the largest payload
a vote of clients
the highest timestamp
data that should be merged, like counters or sets
a session timestamp
a profile photo URL
a single-value overwrite
27. How does Kafka guarantee message ordering?
Kafka guarantees order within a single partition. Each partition is an append-only log, and every record receives a monotonically increasing offset. Consumers read in offset order.
Across partitions there is no ordering guarantee. To keep related events in order, produce them with the same key, since the default partitioner hashes the key to pick the partition.
producer.send(new ProducerRecord<>("orders", orderId, event));
For strict order with retries, enable enable.idempotence=true, or keep max.in.flight.requests.per.connection at 5 or less with idempotence on, so retries cannot reorder a batch.
Take quiz
a single partition
the entire cluster
every consumer group simultaneously
all topics
use many topics
use the order ID as the message key
disable offsets
send them to random partitions
28. Why does Kafka only guarantee order within a partition?
Because partitions are the unit of parallelism. Each partition is written by one leader broker sequentially, which makes ordering cheap. A global order across partitions would force all writes through a single sequencer and kill scalability.
Different partitions live on different brokers and are consumed by different consumers at different speeds, so any cross-partition interleaving you see is arbitrary.
| One partition | Many partitions |
| Total order, single writer, limited throughput. | Higher throughput and consumer parallelism. |
| Simple consumers. | Order only per key, not global. |
The design choice is: if you need global order, use one partition (and accept the throughput limit); otherwise partition by a key so order matters only where it needs to.
Take quiz
more brokers
a single partition or sequencer
no offsets
vector clocks
encryption
clock synchronization
parallelism and scalability
GUI features
29. How do you preserve order when using multiple consumers?
Make sure all events that must be ordered are routed to one consumer at a time. In practice that means partitioning by an ordering key and giving each partition to exactly one consumer in the group.
- Choose a key such as
accountIdororderId. - Process each partition sequentially, or use per-key queues inside the consumer if you add a thread pool.
- Commit the offset only after processing, so a crash cannot skip an event.
- Avoid parallel handlers that process messages of the same key concurrently.
If you use a worker pool without per-key affinity, messages can finish in a different order than they were read, even though Kafka delivered them in order.
Take quiz
skip offset commits
process all messages at once
route each key to the same worker
use random workers
every consumer
all producers
no consumer
exactly one consumer
30. How does a sequencer provide total ordering?
A sequencer is a single node (or a replicated group) that assigns a global sequence number to every event. Everyone applies events in that number order.
sequenceDiagram participant P as Producer participant S as Sequencer participant R1 as Replica 1 participant R2 as Replica 2 P->>S: event S->>S: assign seq=42 S->>R1: (42, event) S->>R2: (42, event)
Replicas keep a "next expected" number and buffer anything that arrives early, so all end in the same state.
It is simple and fast, but the sequencer is a bottleneck and a single point of failure. Production systems replicate it with Raft or Paxos, or batch the sequence numbers to reduce load.
Take quiz
adding random delays
sending events twice
using only wall-clock time
assigning a global sequence number to each event
bottleneck and single point of failure
it only works for reads
too many clocks
no ordering at all
31. What is total order broadcast?
Total order broadcast (atomic broadcast) is a messaging primitive with two guarantees: every correct node delivers the same set of messages, and delivers them in the same order.
It is the building block for state machine replication. If every replica starts in the same state and applies the same commands in the same order, they stay identical.
Properties usually stated:
- Validity - a message broadcast by a correct node is eventually delivered.
- Agreement - if one node delivers a message, all correct nodes do.
- Total order - any two nodes deliver messages in the same sequence.
Raft, Zab (ZooKeeper) and Paxos-based logs are practical implementations.
Take quiz
in the same order
in random order
without any agreement
only once per day
GPS positioning
state machine replication
image compression
DNS caching
32. How is total order broadcast related to consensus?
The two problems are equivalent in asynchronous systems with crash failures. You can build one from the other.
- Consensus from TOB: everyone broadcasts a proposal, and all decide on the first message delivered.
- TOB from consensus: run a sequence of consensus instances, where instance k decides which message gets position k.
That is how Multi-Paxos and Raft work in practice: each log slot is one consensus decision.
The FLP result says deterministic consensus cannot be guaranteed in a purely asynchronous system with even one crash, so real systems rely on timeouts and leader election to make progress, giving up liveness (not safety) in bad periods.
Take quiz
a hash table
a sequence of consensus instances, one per log position
a single vector clock
only NTP
clock drift in GPS
Kafka partitions
impossibility of guaranteed consensus in asynchronous systems with a crash
TLS handshakes
33. How do Raft logs establish event ordering?
In Raft the leader appends each client command to its log at the next index, tagged with the current term. Followers replicate entries in order, and an entry is committed once a majority has stored it.
The pair (term, index) defines position. The Log Matching property says that if two logs have an entry with the same index and term, all earlier entries are identical.
Every node applies committed entries in index order, so every state machine sees the same sequence. A new leader must have the most up-to-date log (election restriction), so committed entries are never reordered or lost.
Order is therefore decided by one leader per term, with consensus protecting it across leader changes.
Take quiz
was sent twice
was seen by one follower
has been stored by a majority of nodes
has the oldest timestamp
the leaders are equal
timestamps are equal
the logs differ completely
all preceding entries are identical
34. How do you handle out-of-order events in stream processing?
You accept that events arrive late and design for it. The common tools are:
- Event-time processing - window by the timestamp in the event, not arrival time.
- Watermarks - an estimate of how far event time has progressed, used to decide when a window can close.
- Allowed lateness - keep window state for some extra time and update results when late data arrives.
- Side outputs - route events that are too late to a dead-letter stream for correction.
- Buffer and sort - hold a short reorder buffer when strict order is needed.
The trade-off is latency versus completeness: a longer lateness bound gives more accurate results but delays output and increases state size.
Take quiz
the arrival order only
the consumer's CPU time
the partition number
the timestamp inside the event
accept late events after the watermark passes
skip checkpointing
ignore all input
delete the stream
35. What are watermarks in stream processing?
A watermark is a marker flowing through the stream that says: "I do not expect any more events with event time earlier than T." It lets the system close event-time windows without waiting forever.
A common strategy is bounded out-of-orderness: watermark = maxEventTimeSeen - maxDelay. With a 5-second delay, once an event with time 12:00:10 arrives, the watermark is 12:00:05 and windows ending before that can fire.
WatermarkStrategy .<Event>forBoundedOutOfOrderness(Duration.ofSeconds(5)) .withTimestampAssigner((e, ts) -> e.getEventTime());
Watermarks are heuristics. If set too tight, many events are late. If too loose, results are delayed.
Take quiz
no earlier-timestamped events are expected after it
the job has failed
events are encrypted
all data is deleted
duplicate partitions
many events to be classified as late
excess memory use only
no windows to ever close
36. What is the difference between event time and processing time?
Event time is when the event actually happened at the source. Processing time is when the system handles it.
| Event time | Processing time |
| Taken from a timestamp in the event. | Taken from the processing machine's clock. |
| Results are deterministic and reproducible on replay. | Results change with load, retries and delays. |
| Needs watermarks to handle lateness. | No lateness concept, simple and low latency. |
| Right for analytics, billing, sessionization. | Fine for monitoring dashboards and rough alerts. |
Example: a mobile app records a click offline at 09:00 and uploads it at 09:40. Event time says 09:00, processing time says 09:40, and reports about 09:00 traffic should include it.
Take quiz
09:20
09:00
unknown always
09:40
Random time
Arrival jitter
Event time
Processing time
37. How do you make consumers idempotent when events are duplicated or reordered?
An idempotent consumer produces the same final state no matter how many times, or in what order, it sees an event. Message brokers usually give at-least-once delivery, so duplicates are normal.
- Event ID table - record processed IDs and skip repeats.
- Version check - apply an update only if its version is higher than the stored one.
- Natural idempotency - use
SET balance = Xstyle or upserts instead of increments. - Commutative operations - use CRDT-like merges so order does not matter.
UPDATE account SET balance = :b, version = :v WHERE id = :id AND version < :v;
The conditional update above silently ignores stale or duplicated events, which handles reordering as well.
Take quiz
increasing latency on purpose
deleting the table
ignoring stale or duplicate events
removing the primary key
Sending an email
Appending to a list
Incrementing a counter by 1
Setting a field to an absolute value
38. What is the difference between linearizability and sequential consistency?
Both require all operations to appear in one total order that respects each process's own program order. Linearizability adds one more rule: the order must respect real time.
| Linearizability | Sequential consistency |
| Total order that matches real-time order of non-overlapping operations. | Total order that only preserves per-process order. |
| A completed write is visible to any read that starts after it. | A read may return an older value, as long as the global order is consistent. |
| Composable across objects. | Not composable. |
| Used by etcd, ZooKeeper writes, Spanner. | Used in some memory models and weaker stores. |
Linearizability is stronger and more expensive because it needs coordination and cannot stay available during a partition (CAP).
Take quiz
alphabetical order
vector clock size
message size
real-time order
etcd
A plain CDN cache
Browser local storage
DNS caches
39. What is causal consistency?
Causal consistency guarantees that operations that are causally related are seen by all clients in the same order, while concurrent operations may be seen in different orders.
It usually builds on four session guarantees: read-your-writes, monotonic reads, monotonic writes and writes-follow-reads.
Example: on a social network, a comment must never be visible without the post it replies to. Two unrelated posts can still appear in different order on different replicas.
It is the strongest consistency model that stays available under network partitions, which is why systems such as COPS and MongoDB causal sessions use it. The cost is tracking dependencies, usually through vector clocks or dependency metadata.
Take quiz
causally related operations
no operations
only the oldest operations
all operations globally
It guarantees linearizability
It stays available during partitions
It requires zero metadata
It eliminates replicas
40. How does eventual consistency treat event ordering?
Eventual consistency promises only that, if updates stop, all replicas converge to the same value. It does not promise anything about the order in which replicas see updates in the meantime.
So a reader may see old data, or may see updates in a different order than another reader. Convergence is achieved through a conflict-resolution rule such as LWW, vector clocks with merge, or CRDTs.
Applications built on it must tolerate temporary anomalies, such as a deleted item reappearing. When ordering matters for a specific key, add stronger guarantees only for that key, for example with quorum reads and writes or causal sessions.
Take quiz
operations are totally ordered in real time
replicas converge once updates stop
every read returns the latest write
no conflicts ever occur
losing the network card
a compile error
reading stale data
disk full
41. What problem do dotted version vectors solve?
Dotted version vectors (DVVs) fix sibling explosion and false conflicts in plain version vectors when many clients write through the same server.
With client-id-free version vectors, two clients writing concurrently through one server can end up with the same vector, so the system cannot tell the writes apart and may drop one, or it must keep growing the vector with client IDs.
A DVV adds a single "dot" (replicaId, counter) that uniquely identifies the latest write, apart from the causal history summarized in the vector. This lets the server tell exactly which siblings a new write supersedes.
Riak adopted DVVs to keep metadata bounded by the number of replicas, not clients.
Take quiz
CPU temperature
disk latency
false conflicts and sibling explosion
packet size
a database index
a client's password
the network route
the specific latest write event
42. How do you troubleshoot out-of-order events in production?
Start by finding where order is lost, not by guessing.
- Check the source - are events produced by multiple threads or instances without a shared key?
- Check partitioning - are related events landing on different partitions or queues?
- Check retries - an async producer with retries and several in-flight requests can reorder batches.
- Check consumers - parallel handlers or thread pools can finish out of order.
- Compare clocks - look at NTP offsets and the timestamps used for sorting.
- Trace with IDs - log a sequence number or correlation ID at each hop to see the first place order breaks.
Then fix at the right layer: add a key, enable idempotent producers, add sequence numbers with a reorder buffer, or use version checks in the consumer.
Take quiz
a long topic name
small message headers
too much disk space
retries with multiple in-flight requests
add sequence or correlation IDs to find where order breaks
delete the topic
increase clock speed
restart every server
43. What happens to event ordering during a network partition?
When a partition splits the cluster, each side can no longer see the other's events, so a single consistent order cannot be maintained without sacrificing something. This is the CAP trade-off.
| Choice | Effect on ordering |
| CP (consistent) | Only the majority side keeps ordering writes; the minority rejects or stalls, so one order exists. |
| AP (available) | Both sides accept writes independently, creating concurrent histories that must be merged when the partition heals. |
After healing, an AP system uses vector clocks, LWW or CRDTs to reconcile. A CP system using Raft just catches the minority up from the leader's log.
The key lesson is that you cannot have strict global order and full availability at the same time during a partition.
Take quiz
stops accepting writes
deletes its log
accepts all writes freely
creates its own leader permanently
a firewall
vector clocks, LWW or CRDTs
only manual DNS changes
disk defragmentation
44. How does event sourcing preserve ordering within an aggregate?
Each aggregate (for example one order or one account) has its own event stream, and every event carries a monotonically increasing version number. Order is guaranteed per aggregate, not globally.
When saving, the writer states the version it expects. The store appends only if the stream is still at that version, otherwise it raises a concurrency conflict (optimistic concurrency).
append(streamId="order-77", expectedVersion=4, events=[ItemAdded]) -- fails if current version != 4
This prevents two writers from interleaving conflicting events in the same stream. Cross-aggregate order is deliberately not guaranteed, which keeps writes scalable.
Take quiz
globally across all aggregates
within each aggregate's event stream
only by wall-clock time
only for deleted events
a DNS lookup
a global sleep
an expected version check on append
random delays
45. When would you choose a logical clock over TrueTime or NTP?
Choose a logical (or hybrid) clock when you need causal correctness and cannot afford or provide tightly synchronized hardware clocks.
| Option | Best when | Cost |
| NTP / wall clock | Logs, TTLs, coarse ordering | Error of ms, can step backward |
| TrueTime-style | Global external consistency needed, you control the hardware | GPS/atomic clocks, commit wait |
| Lamport / vector | Causality or conflict detection matters, no special hardware | Metadata overhead, no real-time meaning |
| HLC | You want causality and human-readable time | Slight complexity |
Example: a multi-master key-value store on commodity cloud VMs should use vector clocks or HLC, not raw NTP timestamps, to detect conflicts safely.
Take quiz
Raw NTP timestamps with LWW
GPS-based TrueTime only
Vector clocks or HLC
No metadata
only HTTP
only a database index
no replication
tightly synchronized hardware clocks
46. How can you optimize vector clock size?
Vector clocks grow with the number of writers, so large deployments shrink them with a few techniques:
- Track replicas, not clients - use version vectors with one entry per server.
- Dotted version vectors - avoid extra entries just to separate concurrent client writes.
- Pruning - drop the oldest entries beyond a limit, as Dynamo did, accepting rare false conflicts.
- Interval tree clocks - allow participants to join and leave without unbounded growth.
- Compression and delta encoding - send only the entries that changed.
Pruning is the riskiest because losing causal history can turn an ordered pair into a seemingly concurrent one, causing extra merges. Choose the technique based on how often writers change.
Take quiz
clocks become random
timestamps are removed
replicas stop writing
there are usually far fewer replicas than clients
false conflicts due to lost causal history
more disk space freed for no reason
faster reads
stronger ordering
47. How does the transactional outbox pattern help event ordering?
The outbox pattern writes the business change and the event to an outbox table in the same database transaction. A separate relay then publishes outbox rows to the broker.
Because both rows commit atomically, you never publish an event for a rolled-back change, or lose an event for a committed one. The relay reads rows in insertion (or sequence) order, so events from one aggregate reach the broker in the order they were committed.
flowchart LR A["App transaction"] --> B[(Business table)] A --> C[(Outbox table)] C --> D["Relay / CDC"] D --> E["Message broker"]
Use the aggregate ID as the message key so the broker keeps that order per partition. Consumers must still be idempotent, since the relay may publish a row twice.
Take quiz
in the same database transaction
only after a restart
in separate unrelated systems
without any storage
random keys
the aggregate ID as message key
a new topic per event
no keys
48. Explain the execution flow of causal delivery with vector clocks?
Causal delivery holds back a received message until everything it depends on has been delivered locally.
Each message from process j carries vector VM. Receiver i with local vector V delivers it only when:
VM[j] == V[j] + 1- it is the next message from j, andVM[k] ≤ V[k]for every other k - the receiver has already delivered all messages the sender had seen.
flowchart TD
A["Message arrives"] --> B{Next from sender and dependencies met?}
B -- Yes --> C["Deliver and update local vector"]
B -- No --> D["Put in hold-back queue"]
C --> E["Recheck queued messages"]
D --> E
After delivery, V[j] is incremented and the hold-back queue is rechecked, since a delivery may unblock waiting messages.
Take quiz
it arrives first
it is the next from its sender and its dependencies were delivered
its size is small
its timestamp is the lowest overall
sent back to the producer
encrypted twice
held in a hold-back queue
discarded forever
49. How does causal broadcast work?
Causal broadcast delivers every message to all nodes so that if broadcast(m1) happened before broadcast(m2), every node delivers m1 before m2.
A typical algorithm:
- The sender increments its own vector clock entry and attaches the vector to the message.
- The message is sent (often via reliable broadcast) to all nodes, including itself.
- Each receiver checks the causal delivery condition and queues the message if not satisfied.
- When delivered, the receiver merges the vector clocks.
It needs only reliable point-to-point links and no central coordinator, so it scales and stays available. Unlike total order broadcast, concurrent messages may be delivered in different orders on different nodes.
Take quiz
Yes, a SQL server
Yes, a GPS device
No, it works with vector clocks and local checks
Yes, always
only twice
in the same order always
never
in different orders at different nodes
50. How do CRDTs avoid the need for strict event ordering?
CRDTs (conflict-free replicated data types) are designed so that operations or states commute: applying them in any order, any number of times, gives the same result. Replicas therefore converge without agreeing on an order.
| State-based (CvRDT) | Operation-based (CmRDT) |
| Ships full state; merge is a join (max, union). | Ships operations; needs causal, exactly-once delivery. |
| Tolerates duplicates and reordering. | Tolerates concurrent ops if they commute. |
| Example: G-Counter, OR-Set. | Example: collaborative text editing ops. |
Example: a grow-only counter keeps one count per replica and merges with element-wise max, so order and duplicates do not matter.
The price is that data models are limited. Operations like "withdraw if balance is enough" are not commutative and still need coordination.