How Often Should You Rotate, and Where Should Keys Live?
Every security team ends up asking the same two questions about encryption keys:
- How often should we rotate them?
- Where should we store them? A config file, a self-hosted vault, a cloud KMS, or a hardware security module (HSM)?
Rotate too rarely and one leaked key exposes months of data. Rotate too often and you pay for it in operations: re-wrapping data keys, redeploying services, coordinating teams, handling incidents when something breaks. Storage works the same way. An HSM is very hard to compromise but expensive, while a key in a local file costs nothing until the day it leaks.
In this post we treat this as an optimization problem. We build a cost model, solve it in Python, check it with a Monte Carlo simulation, and show the results in a 2×3 dashboard that includes a 3D cost surface.
The Example Problem
A mid-sized SaaS company encrypts four classes of data. Each class has its own data volume and its own cost per exposed gigabyte (regulatory fines, notification costs, fraud, reputational damage):
| Data class | Data encrypted per day $D_c$ [GB] | Loss per exposed GB $L_c$ [$] |
|---|---|---|
| Customer PII | 20 | 200 |
| App logs | 200 | 2 |
| Backups | 500 | 30 |
| Payment tokens | 5 | 5000 |
Four storage options are available. Each has a yearly key-compromise rate, a fixed yearly cost, a cost per rotation, and a mean detection delay (how long a compromise goes unnoticed):
| Storage $s$ | Compromise rate $\lambda_s$ [1/yr] | Fixed cost $F_s$ [$/yr] | Rotation cost $C_s$ [$] | Mean detection delay $\delta_s$ [days] |
|---|---|---|---|---|
| Local file | 0.30 | 0 | 400 | 120 |
| Self-hosted vault | 0.08 | 6,000 | 150 | 45 |
| Cloud KMS | 0.02 | 2,400 | 40 | 10 |
| HSM | 0.004 | 18,000 | 60 | 5 |
Goal: choose a storage backend $s_c$ and a rotation interval $T_c \in [1, 365]$ days for each data class so that the total expected yearly cost is as low as possible. A backend’s fixed cost is paid once, no matter how many classes share it.
Building the Cost Model
Exposure window of a single compromise
Take one key that lives for $T$ days. Everything encrypted under it, from day $0$ to day $T$, is exposed if the key leaks. Suppose the compromise happens at time $U$ and is detected after a delay $\Delta$:
$$
U \sim \mathrm{Uniform}(0, T), \qquad \Delta \sim \mathrm{Exp}\left(\tfrac{1}{\delta}\right)
$$
The attacker can decrypt data written from the key’s creation up to the moment the key is revoked. Revocation happens either at detection or at the next scheduled rotation, whichever comes first:
$$
X = U + \min(\Delta,; T - U)
$$
Its expectation has a closed form. With $V = T - U \sim \mathrm{Uniform}(0,T)$ and $\mathbb{E}[\min(\Delta, v)] = \delta\left(1 - e^{-v/\delta}\right)$:
$$
\mathbb{E}[X] = \frac{T}{2} + \delta - \frac{\delta^2}{T}\left(1 - e^{-T/\delta}\right)
$$
Annual cost for one class on one backend

The first term falls as $T$ grows and the second term rises, so there is an interior optimum:
$$
T^*_{c,s} = \arg\min_{T \in [1,365]} J_{c,s}(T)
$$
When detection is slow ($\delta \gg T$), $\mathbb{E}[X] \approx T$, which gives the classic square-root rule:
$$
T^* \approx \sqrt{\frac{365, C_s}{\lambda_s L_c D_c}}
$$
Joint storage assignment
Fixed costs are shared, so the classes cannot be optimized one at a time. The full problem is:
$$
\min_{s_1,\dots,s_4}; \sum_{c=1}^{4} J_{c,s_c}!\left(T^*_{c,s_c}\right) ;+; \sum_{s} F_s \cdot \mathbb{1}!\left[\exists, c : s_c = s\right]
$$
There are only $4^4 = 256$ assignments, so we can enumerate them all exactly.
Tail risk
Averages hide the bad years. We simulate the annual loss $Y$ and report Value-at-Risk and Conditional Value-at-Risk:

The number of compromises per year for each class follows $\mathrm{Poisson}(\lambda_s)$.
Source Code
1 | import time |
Code Walkthrough
1. Problem data
The tables above become NumPy arrays: lam, F, C_rot and delta for the storage backends, and D and L for the data classes. Indexing always follows [class, storage], so J_star[c, s] reads as “the cost of putting class c on backend s.”
T_grid covers 1 to 365 days in steps of 0.1 day. That fine grid is the first stage of the optimizer.
2. Analytical cost model
exposure_days(T, d)implements $\mathbb{E}[X] = \frac{T}{2} + \delta - \frac{\delta^2}{T}(1 - e^{-T/\delta})$. It is written entirely with NumPy operations, so it accepts a scalar, a 1D grid or a 3D cube, which the sensitivity analysis needs later.variable_cost(T, s, c, lam_scale)returns the two parts of $J_{c,s}(T)$ separately: rotation cost and expected breach loss. Keeping them apart lets us draw the stacked breakdown chart. Thelam_scaleargument multiplies $\lambda_s$ so we can test what happens if the threat environment gets worse or better.
Two-stage optimization. For each of the 16 (class, storage) pairs:
- Evaluate $J$ on all 3,641 grid points in one vectorized call and take
argmin. - Refine with
scipy.optimize.minimize_scalar(method="bounded")inside the bracket formed by the neighboring grid points.
The grid step guarantees we find the right basin, even when the optimum sits at the boundary. Brent’s method then makes it precise. The if hi > lo guard handles the edge case where the optimum lands on the first or last grid point.
3. Joint assignment with shared fixed costs
itertools.product(range(4), repeat=4) generates all 256 storage assignments as a (256, 4) array. All of them are scored at once without a Python loop:
J_star[np.arange(n_c), assign]uses fancy indexing to pick the right $J^*$ for every class in every assignment, then sums each row.- The boolean matrix
usedmarks which backends each assignment uses, so(used * F).sum(axis=1)charges each backend’s fixed cost only once.
The baseline is the “do nothing” policy: every key in a local file, rotated once a year.
4. Monte Carlo simulation and the speed-up
The model above is analytical. To see the full loss distribution, including the tails, we simulate years of operation.
simulate_naiveis the textbook version: loop over years, then classes, then each compromise event, drawing random numbers one at a time. It is easy to read but slow, because the work runs in Python loops.simulate_fastproduces the same distribution with vectorized NumPy:- Draw all yearly event counts in one call:
k = rng.poisson(lam[s], size=n_years). - Draw all
m = k.sum()compromise times and detection delays at once. - Compute every event’s loss in one vector expression with
np.minimum. - Map each event back to its year with
np.repeat(np.arange(n_years), k)and add up the losses per year withnp.bincount(..., weights=loss).
- Draw all yearly event counts in one call:
The code times both versions on 20,000 simulated years and prints the speed-up, which comes out at roughly 30–60×. The fast version then runs 500,000 years for each policy to get stable estimates of $\mathrm{VaR}{99}$ and $\mathrm{CVaR}{99}$.
5. Sensitivity data
- 3D surface: for Customer PII on Cloud KMS, we evaluate total cost over a $120 \times 100$ grid of $T$ (1–365 days) and breach-rate multiplier (0.1× to 10×). For each multiplier, the row-wise
argmintraces the path of the optimal $T^*$. - $T^$ heat map:* a 3D cube of shape $(\lambda, C_{rot}, T)$ is evaluated in one broadcast expression, and
argmin(axis=2)gives the optimal rotation interval for every combination of breach rate and rotation cost. That is 14,400 optimizations in one NumPy call.
6. Plotting
One figure holds a 2×3 grid built with add_subplot(2, 3, k). Panel 3 uses projection="3d". The axes that span orders of magnitude use log scales. The panel-6 title deliberately avoids two $ signs, because Matplotlib would read the text between them as math.
Execution Results
=== Optimal T* [days] for each (class, storage) ===
Local file Self-hosted vault Cloud KMS HSM
Customer PII 11.2 13.7 16.4 51.8
App logs 36.6 47.6 58.8 165.3
Backups 5.7 6.9 7.8 26.1
Payment tokens 4.4 5.3 5.9 19.8
=== Optimal variable cost J* [$/yr] (without fixed cost) ===
Customer PII 26,271 8,174 1,953 909
App logs 8,174 2,463 550 272
Backups 51,062 16,011 3,959 1,865
Payment tokens 65,979 20,728 5,173 2,472
=== Best joint policy ===
Customer PII -> Cloud KMS rotate every 16.4 days
App logs -> Cloud KMS rotate every 58.8 days
Backups -> Cloud KMS rotate every 7.8 days
Payment tokens -> Cloud KMS rotate every 5.9 days
Fixed cost : $2,400/yr
Variable cost: $11,634/yr
Total : $14,034/yr
Baseline (local file, 365-day rotation): $3,530,494/yr
Reduction: 99.6%
Monte Carlo 20,000 years: loop 0.577s, vectorized 0.0121s (x47 faster)
Baseline mean=$ 3,526,623 VaR95=$ 12,728,307 VaR99=$ 18,396,000 CVaR99=$ 21,841,976
Optimized mean=$ 6,187 VaR95=$ 51,870 VaR99=$ 147,317 CVaR99=$ 154,034

Interpreting the Results
The optimal policy
The optimizer puts all four data classes on Cloud KMS, with rotation intervals that differ a lot:
| Data class | Storage | Optimal rotation $T^*$ |
|---|---|---|
| Customer PII | Cloud KMS | ≈ 16 days |
| App logs | Cloud KMS | ≈ 59 days |
| Backups | Cloud KMS | ≈ 8 days |
| Payment tokens | Cloud KMS | ≈ 6 days |
The total expected cost is about $14,000 per year ($2,400 fixed plus about $11,600 variable). The baseline costs about $3.5 million per year, so the reduction is more than 99%.
Two lessons stand out:
- There is no single right rotation period. Payment tokens, at $5,000 per exposed GB, should rotate about every 6 days. App logs, at $2 per GB, only need rotation every two months. A blanket “rotate every 90 days” rule rotates logs too often and leaves payment tokens exposed far too long.
- The safest backend is not automatically the best one. On variable cost alone, the HSM wins for every class. Its lower breach rate and 5-day detection delay make $J^*$ roughly half of Cloud KMS’s. But its $18,000 fixed cost outweighs that saving: an all-HSM setup costs about $23,500 a year, against about $14,000 for an all-KMS setup. The joint enumeration catches this because it charges fixed costs only once per backend. Optimizing each class separately would miss it.
Panel 1: Total cost vs. rotation interval (Customer PII)
Each backend traces a U-shaped curve on log-log axes. On the left, frequent rotation is expensive. On the right, long-lived keys build up exposure. The dots mark each backend’s $T^*$. Notice that the better the backend, the longer you can safely keep a key: the optimum moves from about 11 days for a local file to about 52 days for an HSM. The HSM curve is very flat, so its rotation period matters little. The local-file curve is steep, so getting the period wrong there is costly.
Panel 2: Cost breakdown (Customer PII on Cloud KMS)
The stacked areas show why the optimum exists. The gray band is the fixed KMS fee, which does not depend on $T$. The cyan band (rotation) shrinks like $1/T$. The pink band (expected breach loss) grows roughly linearly once $T \gg \delta$. The dashed line at $T^* \approx 16.4$ days sits where the marginal saving from rotating less often equals the marginal growth in exposure.
Panel 3: 3D cost surface
The 3D plot shows total cost as a function of rotation interval and a multiplier on the breach rate. The red line traces $T^*$ across the surface. As the threat level rises (moving toward the back of the plot), the valley moves toward shorter rotation intervals and the whole surface rises. This is the square-root rule $T^* \propto \lambda^{-1/2}$ in visual form. If your threat intelligence says attacks are increasing, your rotation schedule should tighten, roughly in proportion to the square root of the increase.
Panel 4: Monte Carlo loss distribution
The histograms compare simulated annual losses in years with at least one compromise. The baseline (red) is centered in the millions of dollars, and its $\mathrm{VaR}{99}$ is about $18 million. The optimized policy (green) moves the whole distribution down by two to three orders of magnitude, with $\mathrm{VaR}{99}$ around $150,000. The simulated means match the analytical expected breach losses, which confirms the closed-form exposure formula. The optimization lowers the average cost, and it also removes most of the catastrophic tail, which is what a risk committee cares about.
Panel 5: Optimal rotation map
This heat map is a quick lookup tool. For a given breach rate (x-axis) and cost per rotation (y-axis), the color shows $T^*$, and the white contours mark 7, 30, 90 and 180 days. The contours are straight diagonal lines on log-log axes, which matches $T^* \propto \sqrt{C_{rot}/\lambda}$. In practice there are two ways to shorten the safe rotation period:
- Lower the cost per rotation through automation (moving down the plot).
- Accept a higher threat level and pay for frequent rotation (moving right).
Automating rotation is what makes short rotation periods affordable.
Panel 6: Cost by data class
On a log scale, the baseline’s variable cost for each class (red) runs from tens of thousands to millions of dollars a year. The optimized cost (green) is about $10^3$ for every class. The labels show the backend and rotation interval chosen for each class. Payment tokens and backups gain the most: they have the highest $L_c D_c$ and therefore the most exposure to remove.
Takeaways
- Key rotation is a trade-off between operational cost, which scales with $1/T$, and exposure from a leaked key, which grows with $T$. A simple model makes that trade-off explicit and solvable.
- The optimal interval follows $T^* \approx \sqrt{365,C_s / (\lambda_s L_c D_c)}$. High-value data should rotate more often, and automation makes that cheap.
- Detection speed $\delta$ matters as much as prevention. A fast-detecting backend caps the exposure window no matter how long the rotation period is.
- Storage choice is a portfolio decision. Shared fixed costs mean you must optimize all data classes together. The most secure option per class is not always the best overall.
- Vectorizing the Monte Carlo simulation with NumPy (
poissonwithsize,repeat,bincount) makes simulating hundreds of thousands of years fast enough for quick what-if analysis of tail risk.
















