The idea: jump from one event to the next

In a bank, the only moments that matter are when a customer walks in and when one leaves. Between them nothing changes: the line stays the same length and the teller stays busy or idle. A discrete-event simulation uses that. It keeps a list of the things that will happen, each with a time, and runs a loop of three lines: take the earliest event, move the clock to its time, and run the code for that kind of event. That code may add new events to the list.

A loop of four boxes: the future event list, a min-heap holding DEP C1 at 8.266 and ARR C2 at 8.665; pop the root; the clock jumps from 8.020 to 8.266; the handler updates state and counters and schedules new events, which go back into the list.
The whole engine is one loop: pop the earliest event, jump the clock, run its handler, push what it schedules.

The page simulates the classic example from Law and Kelton's textbook: a bank with one teller. Customers arrive on average every 1.0 minute and need on average 0.8 minutes of service. The run stops when 20 customers have finished waiting. Demo: start the bank runs the start-up and the first two events, one step at a time. The same queue, run for 100 000 customers and compared with the formulas, is on the M/M/1 queue page.

The parts of the engine

PartIn the bank
Clockthe simulated time in minutes; it only moves when an event is taken
Future event listpending events (time, ARRIVAL or DEPARTURE, customer)
Stateteller busy or idle, B(t); customers waiting, Q(t); their arrival times
Event handlersone routine per event type: what changes, what gets scheduled
Statistical counterscustomers delayed, total delay, area under Q(t), area under B(t)
Random-number generatorgives the gaps between arrivals and the service times

The future event list is a min-heap

The loop always needs the earliest event, so the list is kept as a min-heap on time: the earliest event sits at the root, slot [0], and the parent of slot [i] is slot [(i − 1)/2]. A new event goes into the first free slot and sifts up while it is earlier than its parent. Taking the root moves the last entry to the top and sifts it down. Both cost O(log n) for n pending events. Ties are broken by the order of scheduling, so a run is always the same. The heap itself is on the priority queue page.

In the first event, C1 arrives at 8.020. Its handler schedules the next arrival, C2 at 8.665, and C1's departure at 8.266. The departure is earlier, so it sifts up and becomes the root. With one teller the list never holds more than two events: the next arrival and the departure of the customer in service. A bank with c tellers holds up to c + 1, and a network simulator holds thousands, which is where the heap pays off.

The two event handlers

EventChange the stateSchedule
ARRIVAL of Ckteller idle: Ck is served at once (delay 0) and the teller becomes busy; teller busy: Ck joins the tail of the queue with its arrival timethe next arrival, C(k+1); Ck's departure if it was served
DEPARTURE of Ckqueue empty: the teller becomes idle; otherwise the head Cj goes to the teller, and its delay = now − its arrival timeCj's departure

An arrival always schedules the next arrival. That one line keeps customers coming for the whole run; the list starts with a single event, the first arrival, scheduled by the initialisation at clock 0. Demo: a queue builds shows C6, C7 and C8 arriving while C5 is served, and then C6 reaching the teller after waiting 0.429 minutes.

Statistical counters and the area under Q(t)

A delay is easy to count: when a customer reaches the teller, add the wait to the total. The average queue length needs more care, because it is an average over time. Q(t) is a step function: it is constant between events. So just before each event, the engine adds Q × (time since the last event) to area Q, and B × (time since the last event) to area B. At the end, average Q = area Q ÷ T and utilisation = area B ÷ T.

A step graph of Q(t) from minute 13 to 27 with the area under it shaded. Each step is a rectangle Q times delta t. One wide rectangle from 22.892 to 25.909 at height 4 is marked 4 × 3.017 = 12.068. Below it, B(t) is a bar that is 1 almost all the time.
Q(t) only changes at events, so its area is a sum of rectangles, one per gap between events.

One long service shows it well: C14 is served from 22.892 to 25.909, 3.017 minutes, while 4 people wait. That single gap adds 4 × 3.017 = 12.068 to area Q (Demo: one long service). After 20 customers, the run has handled 39 events and the clock reads 27.004.

Result after 20 customersHow it is computedValue
mean delay in the queuetotal delay ÷ 20 = 50.620 ÷ 202.531 min
average number waitingarea Q ÷ T = 50.620 ÷ 27.0041.875
teller utilisationarea B ÷ T = 16.262 ÷ 27.0040.602
longest queuelargest Q seen7

Area Q equals the total delay here (both 50.620). That is no accident: each waiting customer adds one to Q for as long as they wait, so the area is the sum of the waits. It is Little's law in small form.

Where the random times come from

The numbers come from a Lehmer generator, a linear congruential generator with x(k+1) = 16807 · x(k) mod (2³¹ − 1). Starting from the seed x(0) = 42, it gives 705 894, then 1 126 542 223, then 1 579 310 009. Dividing by 2³¹ − 1 gives U between 0 and 1: 0.000329, 0.524587, 0.735424. The same seed always gives the same stream, so a run can be repeated exactly.

The inverse transform turns U into an exponential time: X = −ln(U) × mean. A U near 1 gives a short time and a U near 0 a long one, with the right probabilities (the exponential distribution page shows why). The first U is tiny because 42 × 16807 is far smaller than 2³¹ − 1, so the first gap is −ln(0.000329) × 1.0 = 8.020 minutes: nobody comes in for eight minutes. The event-driven clock jumps over them in one step.

The curve X = −ln(U) × 0.8 for U from 0 to 1, falling from high values near U = 0 to 0 at U = 1. Draw 3, U = 0.735, maps to a service time of 0.246 minutes; draw 5, U = 0.376, maps to 0.782 minutes.
The inverse transform: a uniform number U goes in, an exponential time −ln(U) × mean comes out.

Event-driven vs fixed time step

The other way to run a model is a fixed time step: move the clock by Δt every pass and check whether anything is due. It is simple, and it fits models that change all the time, like physics. For a bank it wastes passes, and it moves each event to the next tick, so the whole history shifts.

Loop (same bank, same random numbers)PassesIdle passesMean delayAverage Q
event-driven3902.531 min1.875
fixed step Δt = 0.1 min2832471.660 min1.173
fixed step Δt = 0.5 min66360.600 min0.364

With Δt = 0.1 the first 80 passes find nothing to do (Demo: fixed time step Δt = 0.1). With Δt = 0.5 the loop is cheaper, but arrivals and departures that fall in the same half-minute are lumped together and the mean delay drops to less than a quarter of the true value. A smaller step comes closer but needs more passes, almost all of them empty. The event-driven loop gets the exact times with one pass per event. A browser's event loop works the same way: it sleeps until the next task or timer is due instead of polling.

Reading the result

For this bank in the long run the M/M/1 formula gives a mean delay of ρ / (μ − λ) = 0.8 / 0.25 = 3.2 minutes. The run gives 2.531. Twenty customers are too few, and the run starts with an empty bank, which pulls the early delays down. How long to run, what to throw away at the start, and how to put an error bar on the answer is the subject of simulation output analysis. For networks of queues, mean value analysis gives the averages without simulating at all.

See also CPU scheduling, where an operating system's scheduler is itself driven by events: arrivals, completions and timer interrupts.

See also Mean Value Analysis, which gives exact mean values for a closed queueing network without simulating it.

See also 2^k Factorial Design for choosing which simulation runs to make and splitting their variation among the factors.

See also Pooled Queues: M/M/c, which runs three queueing systems on the same seeded customers and checks the results against Erlang C.

What the page leaves out

The page keeps one teller, one stream of random numbers and a stop after 20 customers. Real simulators use several independent streams (one per source of randomness) so that changing one part of the model does not shift the others, and better generators than this 1988 "minimal standard" one, such as MRG32k3a or the Mersenne Twister. It does not show other event-list structures (calendar queues, ladder queues), process-oriented simulation where each customer is a coroutine (as in SimPy), events that cancel other events, a fixed end time with an END event, or parallel simulation across machines.

On the mind map

Open the Distributed Systems mind mapDistributedSystemsReplication: copies of data · what reads seeReplicationPartitioning: split data over nodesPartitioningTime and membership: order events, know who is aliveTime and membershipConsensus: agree on one value or logConsensusTransactions: one change across many servicesTransactionsMessaging: send events between systemsMessagingKafka internals: a replicated append-only logKafka internalsRedis internals: one thread, data in memoryRedis internalsKubernetes: reconcile desired stateKubernetesResilience and speed: stay up and fast under loadResilience and speedCache strategiesCache strategiescache-aside, write-through, write-behindCircuit breakerCircuit breakerstop calling a failing serviceTMR and N-VersionTMR and N-VersionMajority masks one fault, not a shared bugFault Tree AnalysisFault Tree AnalysisMinimal cut sets; AND multiplies, OR 1−ΠToken vs leaky bucketToken vs leaky buckettoken allows bursts; leaky smoothsBackpressureBackpressurebounded queue: block, drop or ask lessLatency vs throughputLatency vs throughputnear full load, queues blow up p99M/M/1 queueM/M/1 queueW = 1/(μ−λ): waits explode as ρ → 1Pooled queues M/M/cPooled queues M/M/cOne shared line beats separate linesMean Value AnalysisMean Value AnalysisRk = Dk(1 + Qk(N−1)), row by rowDiscrete-event simulationPop earliest event, jump clock, run handlerSimulation Output AnalysisSimulation Output AnalysisCorrelated data: batch it or replicate itMonolith vs microservicesMonolith vs microservicesfunction call vs network callDistributed tracingDistributed tracingtraceparent links spans across servicesRate limit windowsRate limit windowsfixed window lets 2x burst at the edgeRetry, backoff and jitterRetry, backoff and jitterWait 2^n plus random, or retries stampedeHedged requestsHedged requestsSlow? Send a copy; take the first replyOpen the Distributed Systems mind mapDistributed Systemsstay up and fast under loadResilience and speedCache strategiesCache strategiescache-aside, write-through, write-behindCircuit breakerCircuit breakerstop calling a failing serviceTMR and N-VersionTMR and N-VersionMajority masks one fault, not a shared bugFault Tree AnalysisFault Tree AnalysisMinimal cut sets; AND multiplies, OR 1−ΠToken vs leaky bucketToken vs leaky buckettoken allows bursts; leaky smoothsBackpressureBackpressurebounded queue: block, drop or ask lessLatency vs throughputLatency vs throughputnear full load, queues blow up p99M/M/1 queueM/M/1 queueW = 1/(μ−λ): waits explode as ρ → 1Pooled queues M/M/cPooled queues M/M/cOne shared line beats separate linesMean Value AnalysisMean Value AnalysisRk = Dk(1 + Qk(N−1)), row by rowDiscrete-event simulationPop earliest event, jump clock, run handlerSimulation Output AnalysisSimulation Output AnalysisCorrelated data: batch it or replicate itMonolith vs microservicesMonolith vs microservicesfunction call vs network callDistributed tracingDistributed tracingtraceparent links spans across servicesRate limit windowsRate limit windowsfixed window lets 2x burst at the edgeRetry, backoff and jitterRetry, backoff and jitterWait 2^n plus random, or retries stampedeHedged requestsHedged requestsSlow? Send a copy; take the first reply
This page on the Distributed Systems mind map · 100 pages in 10 branches · open it to see the whole map and test yourself in recall mode.