A server fails about once every 5 hours and takes about 1 hour to repair. Start it up: at hour 3 it is down with chance 16.2%, and over a year it is up 83.3% of the time. One matrix of rates gives both numbers, with no clock tick.
Set the fail rate and the repair rate, then press Run. Two hundred simulated servers race the exact curve. Then we build, piece by piece, the rates, the holding clocks, the generator Q, the matrix exponential and the simulator that make the two agree.
You need what a probability is, a matrix times a vector and a little Python. We build the rest from zero.
Illustrative toy. Pink is the share of 200 simulated servers that are down (Gillespie, Chapter 8). Yellow is the exact chance from eQt (Chapter 6). The dashed line is the long-run share (Chapter 7). All servers start up.
Chapter 0
See why a model that checks the state once per tick is either blind or wasteful
A server sits in a rack. Right now it is UP. At some moment it fails and drops to DOWN. Later a technician repairs it. You want two numbers: the chance it is down three hours from now, and the share of the year it is up.
The tool you may know is a discrete Markov chain: a model that checks the state once per tick and flips a biased coin. It needs a tick size. A real failure does not wait for a tick. It strikes at 3.7194 hours, or at any other real time.
The top strip is the true life of one server over 24 hours. The bottom strip is what a grid sees when it looks once per tick. Drag the tick.
Illustrative toy: fail rate 0.45 and repair rate 0.9 per hour, so flips are frequent enough to see. A red mark is a flip the grid never sees. A step is idle when the grid sees no change.
A coarse tick is cheap but blind: a failure and its repair can both fit inside one tick. A fine tick sees everything, but almost every step does nothing.
Put a number on the waste. Say the server fails at a rate of 0.2 per hour, once per 5 hours on average. With a tick of 0.001 hours, one hour is 1,000 steps. The chance of a failure in one step is about 0.2 × 0.001 = 0.0002. So about 999.8 of the 1,000 steps change nothing.
A continuous-time Markov chain (CTMC) drops the tick. It describes each state by how fast the system leaves it, and it jumps at real times. It keeps the Markov property: the future depends only on the present state, not on the path that led there.
The failure. Symptom: a model on a one-hour grid reports fewer outages than the event log. Measure: count the flips in the log and the flips the grid sees; the gap is the missed events. Fix: drop the grid and model rates.
Chapter 1
Replace "the chance per tick" with a rate, and turn the rate back into an exact chance for any window
Without a tick, what number says how likely the server is to fail? It cannot be "the chance it fails at this instant". An instant has zero width, so that chance is zero.
A rate is the chance of leaving per unit of time, for a short window. Its unit is 1 per hour. Take a fail rate of 0.2 per hour. In a short window of h hours, the chance of a failure is about 0.2 × h.
For a long window that rule overshoots, and above 5 hours it passes 1. The exact chance comes from chaining short slices. The server survives each slice with chance 1 − q×(slice). Multiply the slices, let them shrink, and the product becomes an exponential.
Call the rate q and the window length h. Call the chance of at least one jump inside the window p(h).
p of h equals one minus e to the minus q h.
Multiply the rate q by the window h. Take e to the minus that product: this is the chance nothing happens. One minus it is p of h.
With q = 0.2 per hour and h = 0.1 hour, q h = 0.02 and p = 1 − e−0.02 = 0.0198. The short rule 0.2 × 0.1 = 0.0200 is off by 1%. At h = 2 hours, p = 1 − e−0.4 = 0.3297, and the short rule 0.40 is off by 21%.
Blue is the short rule, q × h. Yellow is the exact chance. Drag the window and watch them part.
Exact formulas, no simulation. The red band marks chances above 1, which the short rule reaches and a probability never can.
The failure. Symptom: a simulator steps 0.5 hours at a time with p = q × 0.5, and a state with rate 3 per hour gets p = 1.5. Measure: print q × dt for the fastest state. Fix: use 1 − e−q dt, or drop the tick (Chapter 8).
Chapter 2
Find how long a stay lasts, and see that the time already spent tells you nothing about the time left
The server just came up. How long will it stay up? Call this stay the holding time: the time spent in a state before the next jump. Its length depends on one number, the holding rate: the total rate of leaving the state.
A stay outlasts t hours when there is no jump in a window of t hours. Chapter 1 gave that chance. Call the holding time in state i Ti and its holding rate qi.
The probability that T-i is greater than t equals e to the minus q-i t.
Multiply the holding rate q-i by the time t. Then e to the minus that is the chance the stay T-i lasts longer than t. The mean stay is 1 divided by q-i.
UP has qUP = 0.2 per hour, so the mean stay is 1/0.2 = 5 hours. The chance it is still up after 3 hours is e−0.6 = 0.5488. Half of all stays end before ln 2 / 0.2 = 3.47 hours, well before the mean.
Grey bars are 600 simulated stays. Pink bars keep only the stays that outlasted the wait and measure the time left. Drag the wait: pink still follows the yellow curve.
Illustrative toy: 600 exponential draws from a fixed seed. Yellow is the exact density q e−qt, scaled to the bars.
That is memoryless: the time already spent tells you nothing. Given 3 hours up, the chance of 2 more is e−0.2×5 / e−0.2×3 = e−0.4 = 0.6703. A fresh server survives its first 2 hours with the same 0.6703. This is the Markov property in time. The exponential is the only continuous distribution with it.
The failure. Symptom: real disks wear out, so old ones fail sooner, and the CTMC underpredicts late failures. Measure: plot logged up-times against e−qt; a hump instead of a steady decay means wear. Fix: split UP into stages, such as new and worn, so that each stage is memoryless.
Chapter 3
Give each exit its own alarm clock, and read off when the state ends and where it goes
Add a third state. From UP the server can fail (rate 0.2 per hour) or go to planned MAINT, maintenance (rate 0.05 per hour). Which happens first, and when?
Give each exit its own alarm clock. Each clock rings after its own exponential time. The first clock to ring wins: its exit happens, and we throw the other clocks away. The race gives two facts.
Call the rate from state i to state j qij. Call the sum over all exits the holding rate qi, as in Chapter 2.
The probability that the next state is j equals q-i-j over q-i, where q-i is the sum over j not equal to i of q-i-j.
Add the rates of all exits to get q-i. The stay lasts an exponential time at rate q-i. Then exit j wins with chance q-i-j divided by q-i.
From UP, qUP = 0.2 + 0.05 = 0.25 per hour. The mean stay is 1/0.25 = 4 hours, shorter than the 5 hours of failure alone. Then the server goes DOWN with chance 0.2/0.25 = 0.80, or to MAINT with chance 0.05/0.25 = 0.20.
Each lane is one exit's clock. Press Race once to watch a race, or Race 1,000 to fill the tallies. Then change a rate.
Illustrative toy: each race draws two exponential times from a seeded generator. Yellow ticks are the predicted shares qij/qi; the read-out gives the predicted mean stay 1/qi.
The "where" alone is a chain of jumps with no self-loops, called the jump chain (also the embedded chain). The "when" is the holding time. The two are independent: which clock won says nothing about when it rang. So a simulator can draw the time and the destination separately. Chapter 8 does exactly that.
The failure. Symptom: the model says UP lasts 5 hours, the logs say 4. Measure: list every exit of UP in the model. Fix: the holding rate is the sum over all exits, here including maintenance.
Chapter 4
Store every rate in one matrix, and set each diagonal so that probability is never lost
Every rate so far is an arrow between two states. A chain with n states needs one place for all of them. That place is the generator matrix Q: an n × n table where row i holds the rates out of state i.
The entry in row i, column j is qij, the rate of the arrow from i to j. The diagonal needs its own rule. Call the diagonal entry of row i qii.
q-i-i equals minus q-i, which equals minus the sum over j not equal to i of q-i-j.
Add the off-diagonal rates in row i. Put minus that sum on the diagonal. Now every row of Q sums to zero.
States UP, DOWN, MAINT, with repair 1.0 per hour and return from maintenance 0.5 per hour. Row UP: 0.2 + 0.05 = 0.25, so qUP,UP = −0.25. The full matrix is Q = [[−0.25, 0.2, 0.05], [1.0, −1.0, 0], [0.5, 0, −0.5]], and each row sums to 0.
Each slider is one arrow. The matrix fills in live. Press Fill the diagonal to switch the rule off and watch the row sums break.
Rates are per hour. Order of rows and columns: UP, DOWN, MAINT.
Why zero? Probability that leaves state i must arrive somewhere. The diagonal is the outflow from i. The off-diagonals are the same flow, split among the states it reaches. Q holds the whole chain: minus the diagonal is the holding rate, and each off-diagonal divided by it is a jump-chain chance.
The failure. Symptom: chances computed from Q drift above 1, or rows of P(t) sum to 1.08. Measure: print the row sums of Q; they must all be 0. Fix: recompute every diagonal from its row, as in the lab below.
Chapter 5
Let the rates move probability along the arrows, one short step at a time
Q holds rates. You want chances after a finite time: starting UP, the chance to be DOWN at hour 3. Begin with a short step and let the rates move probability.
Use the two-state server: fail rate a = 0.2 and repair rate b = 1.0 per hour, so Q = [[−0.2, 0.2], [1.0, −1.0]]. Write the chance of each state at time t as a row, p(t) = [chance UP, chance DOWN].
In a short step dt, each state sends rate × dt of its probability along each arrow. So p(t + dt) is about p(t) + p(t) Q dt. Divide by dt and let dt shrink to zero.
d-p by d-t equals p of t times Q.
Multiply the row of chances p by Q. Entry j of the result is the flow into state j minus the flow out of j, per hour.
Start UP: p = [1, 0]. Then p Q = [−0.2, 0.2], so DOWN gains chance at 0.2 per hour. One step of dt = 0.1 gives p = [0.98, 0.02]. The exact value at 0.1 hours is [0.9812, 0.0188].
Pink dots are Euler steps of size dt. Yellow is the exact chance of DOWN. Drag dt, then try the fast repair.
Fail rate 0.2 per hour, start UP. Euler: p ← p + p Q dt. Exact: the matrix exponential of Chapter 6.
This is the Kolmogorov forward equation. Stepping it with a fixed dt is the Euler method. At hour 3, Euler with dt = 1 gives 0.168 for DOWN, dt = 0.1 gives 0.1631, and dt = 0.01 gives 0.1622. The exact value is 0.1621. The error falls in proportion to dt.
The failure. Symptom: with a repair rate of 25 per hour and dt = 0.1, the DOWN chance goes negative and swings. Measure: check the smallest entry of p after each step. Fix: keep dt well below 1 divided by the largest rate, or solve the equation exactly.
Chapter 6
Solve the forward equation exactly with P(t) = eQt, and read the chance of every state at any time
The forward equation has the shape of dx/dt = q x, whose answer is x(t) = x(0) eqt. The matrix answer has the same form. Call P(t) the transition matrix. Its entry in row i, column j is the chance to be in state j at time t, from a start in i.
P of t equals e to the Q t, which equals I plus Q t, plus Q t squared over two factorial, plus Q t cubed over three factorial, and so on.
Multiply Q by the time t. Add the powers of Qt, each divided by its factorial. The sum is P of t. Read row i for a start in state i.
Server, start UP, t = 3 hours. For two states the series has a closed form. PUP,UP(t) = b/(a+b) + a/(a+b) × e−(a+b)t = 0.8333 + 0.1667 × e−3.6 = 0.8333 + 0.1667 × 0.0273 = 0.8379. So DOWN at hour 3 has chance 0.1621, the hero's number.
Drag the time. The curves are the chosen start row of P(t). The matrix shows both rows. Then press the wrong button to see e to each entry.
Fail rate 0.2 and repair rate 1.0 per hour. Exact values from the closed form above, which matches scipy.linalg.expm to four decimals.
Three facts make P(t) useful. Its rows sum to 1. It chains: P(3) = P(1) P(2), which is the Markov property again. And as t grows, both rows approach the same row, [0.8333, 0.1667]: the start is forgotten. The term e−(a+b)t sets the speed. It shrinks by a factor of e every 1/1.2 = 0.83 hours.
The failure. Symptom: np.exp(Q*3) returns an entry of 20.09 and rows that do not sum to 1. Measure: check the row sums. Fix: call scipy.linalg.expm(Q*3), the true matrix exponential.
Chapter 7
Find the share of time in each state by balancing the flow in and out of every state
Run the server for a year. What share of the time is it up? As t grows, every row of P(t) tends to one row. Call it the stationary distribution π: the chances that no longer change.
"No longer change" means dp/dt = 0. Put π into the forward equation, and add the rule that chances sum to 1.
Pi times Q equals zero, and the sum over i of pi-i equals one.
For each state, set the flow in equal to the flow out. The flow out of i is pi-i times q-i. The flow in is the sum of pi-j times q-j-i over the other states. Solve these with the rule that the pi-i add to 1.
Server: the flow out of UP is 0.2 πUP and the flow in is 1.0 πDOWN. With πUP + πDOWN = 1, we get 1.2 πUP = 1, so πUP = 0.8333. For the Q of Chapter 4, πDOWN = 0.2 πUP and πMAINT = 0.1 πUP, so πUP = 1/1.3 and π = [0.7692, 0.1538, 0.0769].
Pick a start and press Play. The bars are p(t) for the three-state server. Yellow ticks mark π. Then show the jump-chain shares.
Exact: p(t) = p(0) eQt for the Q of Chapter 4, computed in the page by scaling and squaring.
A trap. The jump chain visits UP on 50% of its jumps, DOWN on 40% and MAINT on 10%. Those count visits, not time. UP lasts 4 hours per visit, DOWN 1 hour and MAINT 2 hours. Weight each visit by its stay: 0.5 × 4 = 2, 0.4 × 1 = 0.4 and 0.1 × 2 = 0.2. Divide by the total 2.6 and you get π back.
π is unique when the chain is irreducible: every state can reach every other state.
The failure. Symptom: a solver given only π Q = 0 returns π = [0, 0]. Measure: check that π sums to 1. Fix: add the row "the shares add to 1" to the system, as in the lab.
Chapter 8
Draw a stay, draw a destination, repeat: an exact sample path with no tick
P(t) gives a cloud of chances. Sometimes you need one concrete life: a log of jumps and times to test a dashboard or a failover script. The Gillespie algorithm makes one exactly, using the race of Chapter 3.
A computer gives uniform random numbers between 0 and 1. Call one U1. Call the stay it produces s.
s equals minus the natural log of U-one, divided by q-i.
Draw U-one. Take its natural log, flip the sign, and divide by the holding rate q-i. A fast state gives a short stay s.
In UP, qUP = 0.25. Draw U1 = 0.5: s = 0.6931/0.25 = 2.77 hours. Then draw U2 = 0.6. The jump chain from UP is DOWN 0.8 and MAINT 0.2, so DOWN covers 0 to 0.8. Since 0.6 < 0.8, the server goes DOWN at hour 2.77.
Why does this work? The stay s exceeds t exactly when U1 < e−qit, and a uniform number does that with chance e−qit. That is the holding time of Chapter 2.
Press Play to run the server, or One jump to see both random draws. Move any rate: the yellow ticks of π move, and the pink shares chase them.
Illustrative toy with a seeded generator. Rates are per hour. Shares are time-weighted from hour 0; changing a rate restarts the count so the shares match the new π.
Every step is a real event, so the cost depends on the number of jumps, not on a time resolution. A seeded numpy run of 5,000 hours on the three-state server makes 1,940 jumps. It spends 76.1% of its time UP, near πUP = 76.9%.
The failure. Symptom: the simulated share of UP comes out near 50%. Measure: compare it with π; check whether you counted jumps or hours. Fix: weight each state by the time spent in it, not by its visits.
Chapter 9
Compute the time to an absorbing state, and list the cases where the model needs care
Some states have no exit. A part goes from WORK to DEG (degraded) at 0.5 per hour, and from DEG to FAILED at 0.3 per hour. FAILED is absorbing: its row of Q is all zeros. Then π = [0, 0, 1], and the useful question is how long the part lasts.
Call the mean time to reach FAILED from state i mi. Look at the first jump: wait the mean stay, then add the mean time still to go from where you land.
m-i equals one over q-i, plus the sum over j of q-i-j over q-i, times m-j.
The mean time m-i is the mean stay in i, plus the average of m-j over where the first jump lands. Write one such line per non-absorbing state and solve them together.
No repair: mDEG = 1/0.3 = 3.33 hours and mWORK = 1/0.5 + 3.33 = 5.33 hours. Add a repair from DEG to WORK at 0.2 per hour. Now qDEG = 0.5, so mDEG = 2 + 0.4 mWORK and mWORK = 2 + mDEG. Then 0.6 mWORK = 4, so mWORK = 6.67 hours.
Set the repair rate, then press Run 500 parts. Pink bars show simulated lifetimes. The yellow line is mWORK from the formula.
Illustrative toy: WORK to DEG at 0.5, DEG to FAILED at 0.3 per hour, simulated with Gillespie from a seeded generator.
Other places where a CTMC needs care:
| Case | Symptom | Fix |
|---|---|---|
| Not memoryless | Logged stays show a hump, not a steady decay. | Split the state into stages. |
| Reducible | Two groups of states never connect; π Q = 0 has many answers. | Model each group alone, or add the missing rates. |
| Stiff rates | Rates of 0.01 and 1,000 in one Q; Euler steps blow up. | Use expm or an implicit solver. |
| Explosion | Rates grow fast with the state, so infinitely many jumps fit in finite time. | Cap the state space. |
| Visits for time | A report gives jump counts as shares of time. | Weight each visit by its stay. |
The failure. Symptom: a reliability report adds the mean stays along the main path and ignores repairs, and the parts last longer than predicted. Measure: compare the logged mean lifetime with the sum of stays. Fix: solve the mi system; it counts every return trip.
Chapter 10
Keep the terms, the numbers, the code and the next steps in one place
A CTMC is a set of states and one generator Q of rates. Each stay is exponential at the holding rate qi. The race of clocks picks the next state with chance qij/qi. The matrix exponential eQt gives every chance at any time, π Q = 0 gives the long run, and Gillespie draws exact lives.
Jobs arrive at a server at rate λ = 2 per minute and finish at rate μ = 3 per minute. The state is the number of jobs. Balance the flow between n and n + 1 jobs: πn+1 × 3 = πn × 2. So each share is 2/3 of the one before.
The shares add to 1 when π0 = 1 − 2/3 = 0.333: the server is idle a third of the time. The mean count is (2/3)/(1/3) = 2 jobs. This is the M/M/1 queue.
| Term | Meaning | Server number |
|---|---|---|
| Rate qij | Chance per hour of the jump i to j, for a short window. | Fail 0.2, repair 1.0 |
| Holding rate qi | Total rate of leaving i; minus the diagonal of Q. | UP: 0.25 with MAINT |
| Holding time | Exponential, mean 1/qi, memoryless. | UP: 5 h mean, median 3.47 h |
| Jump chain | Where the next jump goes: qij/qi. | UP: DOWN 0.8, MAINT 0.2 |
| Generator Q | Rates off the diagonal; rows sum to 0. | [[−0.2, 0.2], [1.0, −1.0]] |
| P(t) = eQt | Chance of j at time t from i; rows sum to 1. | UP to DOWN at 3 h: 0.1621 |
| π | Long-run share of time; π Q = 0. | UP 0.8333 |
| Mean time to absorb mi | Mean stay plus mean time from where you land. | WORK: 5.33 h |
expm, never from np.exp.pythonimport numpy as np from scipy.linalg import expm def generator(rates): # rates[i][j] = q_ij, diagonal ignored Q = np.array(rates, float) np.fill_diagonal(Q, 0) np.fill_diagonal(Q, -Q.sum(axis=1)) # q_ii = -q_i: rows sum to 0 return Q def stationary(Q): # solve pi Q = 0 with sum(pi) = 1 n = len(Q) A = np.vstack([Q.T, np.ones(n)]) b = np.append(np.zeros(n), 1.0) return np.linalg.lstsq(A, b, rcond=None)[0] def gillespie(Q, s, T, rng): # one exact path up to time T t, path = 0.0, [(0.0, s)] while True: q_i = -Q[s, s] if q_i == 0: break # absorbing state t += -np.log(rng.random()) / q_i # the stay s = -ln(U1)/q_i if t > T: break p = Q[s].clip(min=0) / q_i # jump chain row q_ij/q_i s = rng.choice(len(Q), p=p) path.append((t, s)) return path Q = generator([[0, 0.2], [1.0, 0]]) print(expm(Q * 3)[0]) # [0.8379 0.1621] print(stationary(Q)) # [0.8333 0.1667]
Now press Present or Teach and explain from memory: why the tick fails, the race of clocks, the rule for the diagonal of Q, and how eQt and π follow. Then go back to the hero and set a fail rate of 0.5 and a repair rate of 1.5. Predict the dashed line before you press Run.