Minimizing Third-Party Data Sharing with Python

Share Only What Each Vendor’s Contract Requires

Most companies send customer data to outside vendors: a marketing analytics agency, a fraud-scoring service, a university research team. The easy option is to export the whole customer table and let each vendor take what it needs. It is also the riskiest option. Every extra column, every extra row and every extra digit of precision adds exposure, and data protection laws such as GDPR’s data minimisation principle (Art. 5(1)(c)) say you should share only what is “adequate, relevant and limited to what is necessary.”

This article turns that principle into an optimization problem and solves it in Python. Each vendor contract sets out which attributes the vendor needs, how precise they must be, how large anonymity groups must be, and how identifiers are handled. For each vendor, the code finds the smallest release that still meets every one of those terms.


The Problem Setup

We start from a synthetic customer master table with 60,000 records:

Column Type
customer_id, name, email, phone Direct identifiers
age, zip, gender, income, purchase_total Quasi-identifiers (QIs)
consent_marketing, consent_research, fraud_scope Purpose / consent flags

Three vendors each have a contract:

Vendor Rows allowed Required attributes (coarsest acceptable level) Min. class size $k$ Max. suppression Identifiers
Marketing Analytics marketing consent only age ≤ 10-yr band, ZIP ≤ 3 digits, gender raw, purchase ≤ $500 band 10 5% dropped
Fraud Scoring in-scope accounts only ZIP ≤ 4 digits, purchase ≤ $500 band 3 5% pseudonymized token
Academic Research research consent only age ≤ 20-yr band, income ≤ $50k band, gender optional 25 1% dropped

The goal is to find the release for each vendor that shares the least data while meeting its contract.


Mathematical Formulation

Generalization lattice

Each quasi-identifier $j$ has a generalization hierarchy with levels $\ell_j \in {0, 1, \dots, L_j - 1}$. Level $0$ is the raw value and level $L_j - 1$ means the column is removed (suppressed):

  • age: exact → 5-yr → 10-yr → 20-yr → removed ($L=5$)
  • zip: 5 digits → 4 digits → 3 digits → removed ($L=4$)
  • gender: raw → removed ($L=2$)
  • income: $1k → $10k → $50k bands → removed ($L=4$)
  • purchase_total: $1 → $100 → $500 bands → removed ($L=4$)

One candidate release is a vector $\boldsymbol{\ell} = (\ell_{\text{age}}, \ell_{\text{zip}}, \ell_{\text{gender}}, \ell_{\text{income}}, \ell_{\text{purchase}})$. The full lattice has

$$
|\mathcal{L}| = \prod_j L_j = 5 \times 4 \times 2 \times 4 \times 4 = 640
$$

nodes.

Equivalence classes and re-identification risk

For a release $\boldsymbol{\ell}$, two records belong to the same equivalence class if their generalized QI values are identical. Let $|EC(i)|$ be the size of the class that contains record $i$. Under the prosecutor attack model, the probability of re-identifying record $i$ is

$$
r_i(\boldsymbol{\ell}) = \frac{1}{|EC(i)|}.
$$

The release is $k$-anonymous when $\min_i |EC(i)| \ge k$. Records in classes smaller than $k$ may be suppressed, up to the contractual limit $s_{\max}$:

$$
\frac{1}{n}\sum_{i=1}^{n} \mathbf{1}\big[,|EC(i)| < k,\big] \le s_{\max}.
$$

The mean re-identification risk over the records that are actually released ($\mathcal{K}$) is

$$
\bar{R}(\boldsymbol{\ell}) = \frac{1}{|\mathcal{K}|}\sum_{i \in \mathcal{K}} \frac{1}{|EC(i)|}.
$$

Disclosure score and contract utility

Each attribute has a sensitivity weight $w_j$ (income and ZIP count most). The precision kept for an attribute is $1 - \ell_j/(L_j-1)$, so the disclosure score is

$$
D(\boldsymbol{\ell}) = \sum_{j} w_j \left(1 - \frac{\ell_j}{L_j - 1}\right).
$$

Contract utility is the mean retained precision over the attributes the vendor requires, $\mathcal{R}_v$:

Optimization problem

For vendor $v$, with precision limits $\ell_j^{\max}$, anonymity threshold $k_v$ and suppression limit $s_v$:

with $\lambda = 20$. Attributes the vendor does not need have no upper limit on $\ell_j$, so the optimizer always drops them: removing a column lowers $D$ and never raises $\bar{R}$. Two more steps sit outside the lattice and shrink the release further:

  1. Row minimization: only records with the right consent or purpose flag are considered ($n \to n_v$).
  2. Identifier handling: direct identifiers are dropped, or replaced with a vendor-specific keyed hash $\text{token}_v(i) = \text{HMAC-SHA256}(K_v, i)$, so two vendors cannot join their datasets on a shared ID.

The expensive step is counting equivalence-class sizes for every lattice node. The straightforward approach rebuilds a generalized DataFrame for each node and runs groupby(...).transform("size").

The faster version does two things:

  1. Pre-encodes every attribute at every generalization level once, as dense integer codes (np.unique(..., return_inverse=True)).
  2. For each node, combines the codes into a single int64 key with mixed-radix arithmetic,

where $B_j$ is the number of distinct codes for attribute $j$ at its chosen level. A single np.unique(..., return_counts=True) call then gives every record’s class size.

The script runs both methods on the same nodes, uses an assert to check that they return identical results, and prints the measured speed-up. The full search covers 640 nodes for each of the three vendors.


Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import time
import hmac
import hashlib
import itertools
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # noqa: F401

# ------------------------------------------------------------
# 1. Synthetic customer master table
# ------------------------------------------------------------
rng = np.random.default_rng(42)
N = 60_000

zip_prefix = rng.choice(np.arange(100, 125), size=N)
zip5 = zip_prefix * 100 + rng.integers(0, 100, size=N)
age = np.clip(rng.normal(44, 15, size=N).round(), 18, 95).astype(int)
gender = rng.choice([0, 1], size=N)
income = np.clip(rng.lognormal(np.log(55_000), 0.5, size=N), 8_000, 600_000).round(-3).astype(int)
purchase = np.clip(rng.gamma(2.0, 180.0, size=N), 1, 8_000).round(2)
consent_marketing = rng.random(N) < 0.62
consent_research = rng.random(N) < 0.48
active_fraud_scope = rng.random(N) < 0.35

df = pd.DataFrame({
"customer_id": np.arange(1, N + 1),
"name": [f"Customer {i}" for i in range(1, N + 1)],
"email": [f"user{i}@example.com" for i in range(1, N + 1)],
"phone": [f"+1-555-{i:07d}" for i in range(1, N + 1)],
"age": age,
"zip": zip5,
"gender": gender,
"income": income,
"purchase_total": purchase,
"consent_marketing": consent_marketing,
"consent_research": consent_research,
"fraud_scope": active_fraud_scope,
})

# ------------------------------------------------------------
# 2. Generalization hierarchies (level 0 = raw, last level = suppressed)
# ------------------------------------------------------------
QI = ["age", "zip", "gender", "income", "purchase_total"]
LEVELS = {"age": 5, "zip": 4, "gender": 2, "income": 4, "purchase_total": 4}
SENSITIVITY = {"age": 1.0, "zip": 1.5, "gender": 0.5, "income": 2.0, "purchase_total": 1.0}


def generalize(col, values, level):
v = np.asarray(values)
if col == "age":
widths = [1, 5, 10, 20]
if level == 4:
return np.zeros_like(v)
return (v // widths[level]) * widths[level]
if col == "zip":
divs = [1, 10, 100]
if level == 3:
return np.zeros_like(v)
return v // divs[level]
if col == "gender":
return v if level == 0 else np.zeros_like(v)
if col == "income":
widths = [1_000, 10_000, 50_000]
if level == 3:
return np.zeros_like(v)
return (v // widths[level]) * widths[level]
if col == "purchase_total":
widths = [1, 100, 500]
if level == 3:
return np.zeros_like(v, dtype=np.int64)
return (np.floor(v / widths[level]) * widths[level]).astype(np.int64)
raise ValueError(col)


def label_value(col, values, level):
g = generalize(col, values, level)
last = LEVELS[col] - 1
if level == last:
return None
if col == "age" and level > 0:
w = [1, 5, 10, 20][level]
return pd.Series(g).astype(str) + "-" + pd.Series(g + w - 1).astype(str)
if col == "zip" and level > 0:
return pd.Series(g).astype(str) + "*" * level
if col == "income" and level > 0:
w = [1_000, 10_000, 50_000][level]
return pd.Series(g).astype(str) + "-" + pd.Series(g + w - 1).astype(str)
if col == "purchase_total" and level > 0:
w = [1, 100, 500][level]
return pd.Series(g).astype(str) + "-" + pd.Series(g + w).astype(str)
return pd.Series(g)


# ------------------------------------------------------------
# 3. Vendor contracts
# max_level : required attributes and the coarsest level still acceptable
# k : minimum equivalence-class size
# supp : max fraction of records that may be suppressed
# id_mode : "drop" / "pseudonym" / "raw" for direct identifiers
# ------------------------------------------------------------
CONTRACTS = {
"Marketing Analytics": {
"row_filter": "consent_marketing",
"max_level": {"age": 2, "zip": 2, "gender": 0, "purchase_total": 2},
"k": 10, "supp": 0.05, "id_mode": "drop",
},
"Fraud Scoring": {
"row_filter": "fraud_scope",
"max_level": {"zip": 1, "purchase_total": 2},
"k": 3, "supp": 0.05, "id_mode": "pseudonym",
},
"Academic Research": {
"row_filter": "consent_research",
"max_level": {"age": 3, "income": 2, "gender": 1},
"k": 25, "supp": 0.01, "id_mode": "drop",
},
}
LAMBDA = 20.0 # weight of re-identification risk in the disclosure score


# ------------------------------------------------------------
# 4. Equivalence-class statistics: naive (pandas groupby) vs fast (integer keys)
# ------------------------------------------------------------
def class_sizes_naive(frame, levels):
tmp = pd.DataFrame({c: generalize(c, frame[c].values, l) for c, l in zip(QI, levels)})
return tmp.groupby(QI, sort=False)[QI[0]].transform("size").values


def build_codes(frame):
codes = {}
for c in QI:
codes[c] = []
for l in range(LEVELS[c]):
_, inv = np.unique(generalize(c, frame[c].values, l), return_inverse=True)
codes[c].append(inv.astype(np.int64).ravel())
return codes


def class_sizes_fast(codes, levels):
key = np.zeros_like(codes[QI[0]][0])
for c, l in zip(QI, levels):
arr = codes[c][l]
key = key * (int(arr.max()) + 1) + arr
_, inv, cnt = np.unique(key, return_inverse=True, return_counts=True)
return cnt[inv.ravel()]


def evaluate(sizes, k, supp, n):
small = sizes < k
n_supp = int(small.sum())
kept = sizes[~small]
k_min = int(kept.min()) if kept.size else 0
risk = float(np.mean(1.0 / kept)) if kept.size else 1.0
max_risk = float(1.0 / k_min) if k_min else 1.0
return {"k_min": k_min, "supp_rate": n_supp / n, "mean_risk": risk,
"raw_risk": float(np.mean(1.0 / sizes)),
"max_risk": max_risk, "feasible_k": n_supp <= supp * n}


def disclosure(levels):
return sum(SENSITIVITY[c] * (1 - l / (LEVELS[c] - 1)) for c, l in zip(QI, levels))


def utility(levels, contract):
req = contract["max_level"]
vals = [1 - l / (LEVELS[c] - 1) for c, l in zip(QI, levels) if c in req]
return float(np.mean(vals))


LATTICE = list(itertools.product(*[range(LEVELS[c]) for c in QI]))

# ------------------------------------------------------------
# 5. Speed comparison on the full dataset
# ------------------------------------------------------------
sample_nodes = LATTICE[:40]
t0 = time.perf_counter()
for node in sample_nodes:
class_sizes_naive(df, node)
t_naive = (time.perf_counter() - t0) / len(sample_nodes)

codes_all = build_codes(df)
t0 = time.perf_counter()
for node in sample_nodes:
class_sizes_fast(codes_all, node)
t_fast = (time.perf_counter() - t0) / len(sample_nodes)

check_node = (1, 2, 0, 1, 2)
assert np.array_equal(class_sizes_naive(df, check_node), class_sizes_fast(codes_all, check_node))

print("=== Performance ===")
print(f"Lattice nodes : {len(LATTICE)}")
print(f"Naive groupby per node : {t_naive * 1000:8.2f} ms")
print(f"Fast integer-key per node : {t_fast * 1000:8.2f} ms")
print(f"Speed-up : {t_naive / t_fast:8.1f}x")
print(f"Estimated full-lattice naive : {t_naive * len(LATTICE):8.2f} s")


# ------------------------------------------------------------
# 6. Search the lattice for each vendor
# ------------------------------------------------------------
def pseudonymize(ids, vendor):
key = hashlib.sha256(("vendor-secret::" + vendor).encode()).digest()
return [hmac.new(key, str(i).encode(), hashlib.sha256).hexdigest()[:16] for i in ids]


results = {}
tables = {}
for vendor, ct in CONTRACTS.items():
sub = df[df[ct["row_filter"]]].reset_index(drop=True)
n = len(sub)
codes = build_codes(sub)
rows = []
for node in LATTICE:
lv = dict(zip(QI, node))
precision_ok = all(lv[c] <= ct["max_level"].get(c, LEVELS[c] - 1) for c in QI)
sizes = class_sizes_fast(codes, node)
ev = evaluate(sizes, ct["k"], ct["supp"], n)
d = disclosure(node)
rows.append({"node": node, **lv, "disclosure": d,
"utility": utility(node, ct),
"score": d + LAMBDA * ev["mean_risk"],
"precision_ok": precision_ok,
"feasible": precision_ok and ev["feasible_k"], **ev})
tab = pd.DataFrame(rows)
feas = tab[tab["feasible"]].sort_values(["score", "mean_risk"])
if feas.empty:
raise RuntimeError(f"No feasible release for {vendor}")
best = feas.iloc[0]
tables[vendor] = tab

node = best["node"]
sizes = class_sizes_fast(codes, node)
keep = sizes >= ct["k"]
release = pd.DataFrame(index=np.arange(n))
if ct["id_mode"] == "pseudonym":
release["token"] = pseudonymize(sub["customer_id"].values, vendor)
for c, l in zip(QI, node):
lab = label_value(c, sub[c].values, l)
if lab is not None:
release[c] = lab.values
release = release[keep].reset_index(drop=True)

raw_sizes = class_sizes_fast(codes, (0, 0, 0, 0, 0))
results[vendor] = {
"best": best, "release": release, "n_rows_in": n, "sizes": sizes[keep],
"raw_sizes": raw_sizes,
"full_cells": N * (len(df.columns) - 4),
"min_cells": release.shape[0] * release.shape[1],
}

print("\n=== Minimized releases ===")
for vendor, r in results.items():
b = r["best"]
ct = CONTRACTS[vendor]
print(f"\n[{vendor}] k>={ct['k']}, identifiers={ct['id_mode']}")
print(" levels :", {c: int(b[c]) for c in QI})
print(f" rows : {N} -> {r['n_rows_in']} (purpose filter) -> {len(r['release'])} (after suppression)")
print(f" columns : {len(df.columns) - 4} -> {r['release'].shape[1]} {list(r['release'].columns)}")
print(f" cells : {r['full_cells']:,} -> {r['min_cells']:,} "
f"({100 * (1 - r['min_cells'] / r['full_cells']):.1f}% reduction)")
print(f" k_min={b['k_min']}, mean re-id risk={b['mean_risk']:.4f}, "
f"max risk={b['max_risk']:.4f}, suppressed={100 * b['supp_rate']:.2f}%")
print(f" raw-QI mean re-id risk={np.mean(1 / r['raw_sizes']):.4f}")
print(" sample:")
print(r["release"].head(3).to_string(index=False))

# ------------------------------------------------------------
# 7. Visualization (2 rows x 3 columns)
# ------------------------------------------------------------
vendors = list(CONTRACTS)
short = ["Marketing", "Fraud", "Research"]
colors = ["#1f77b4", "#ff7f0e", "#2ca02c"]

fig = plt.figure(figsize=(21, 13))

# (1) Cells shared: full export vs minimized
ax1 = fig.add_subplot(2, 3, 1)
x = np.arange(len(vendors))
full = [results[v]["full_cells"] / 1e3 for v in vendors]
mini = [results[v]["min_cells"] / 1e3 for v in vendors]
ax1.bar(x - 0.2, full, 0.4, label="Full export", color="#bbbbbb")
ax1.bar(x + 0.2, mini, 0.4, label="Minimized", color=colors)
for i in range(len(vendors)):
ax1.text(x[i] + 0.2, mini[i], f"-{100 * (1 - mini[i] / full[i]):.0f}%", ha="center", va="bottom")
ax1.set_xticks(x)
ax1.set_xticklabels(short)
ax1.set_ylabel("Data cells shared (thousands)")
ax1.set_title("(1) Data volume: full export vs minimized")
ax1.legend()

# (2) Disclosure vs risk (Marketing)
ax2 = fig.add_subplot(2, 3, 2)
tab = tables[vendors[0]]
b = results[vendors[0]]["best"]
m_coarse = ~tab.precision_ok
m_kfail = tab.precision_ok & ~tab.feasible
m_ok = tab.feasible
ax2.scatter(tab.loc[m_coarse, "disclosure"], tab.loc[m_coarse, "raw_risk"],
s=10, c="#cccccc", label="Too coarse for contract")
ax2.scatter(tab.loc[m_kfail, "disclosure"], tab.loc[m_kfail, "raw_risk"],
s=30, c="#ff7f0e", label="Fails k-anonymity")
ax2.scatter(tab.loc[m_ok, "disclosure"], tab.loc[m_ok, "raw_risk"],
s=40, c="#1f77b4", label="Fully compliant")
ax2.scatter([b["disclosure"]], [b["raw_risk"]], s=300, marker="*", c="red", label="Selected", zorder=5)
ax2.set_yscale("log")
ax2.set_xlabel("Disclosure score D")
ax2.set_ylabel("Mean re-identification risk")
ax2.set_title("(2) Lattice search: Marketing Analytics")
ax2.legend()

# (3) 3D surface: risk vs age/zip generalization
ax3 = fig.add_subplot(2, 3, 3, projection="3d")
fixed = {c: int(b[c]) for c in ["gender", "income", "purchase_total"]}
sub_t = tab[(tab.gender == fixed["gender"]) & (tab.income == fixed["income"]) &
(tab.purchase_total == fixed["purchase_total"])]
A, Z = np.meshgrid(np.arange(LEVELS["age"]), np.arange(LEVELS["zip"]))
R = np.zeros_like(A, dtype=float)
for _, r in sub_t.iterrows():
R[int(r.zip), int(r.age)] = np.log10(r.raw_risk)
ax3.plot_surface(A, Z, R, cmap="viridis", edgecolor="k", linewidth=0.3, alpha=0.9)
ax3.scatter([b["age"]], [b["zip"]], [np.log10(b["raw_risk"])], c="red", s=200, marker="*")
ax3.set_xlabel("Age level")
ax3.set_ylabel("ZIP level")
ax3.set_zlabel("log10 mean risk")
ax3.set_title("(3) Risk surface (Marketing)")
ax3.view_init(elev=28, azim=-135)

# (4) Equivalence class size distribution
ax4 = fig.add_subplot(2, 3, 4)
bins = np.logspace(0, 4, 40)
ax4.hist(results[vendors[0]]["raw_sizes"], bins=bins, alpha=0.6, color="#999999", label="Raw quasi-identifiers")
for v, c, s in zip(vendors, colors, short):
ax4.hist(results[v]["sizes"], bins=bins, histtype="step", lw=2, color=c, label=s)
ax4.set_xscale("log")
ax4.set_yscale("log")
ax4.set_xlabel("Equivalence class size (records)")
ax4.set_ylabel("Number of records")
ax4.set_title("(4) Equivalence class sizes")
ax4.legend()

# (5) Heatmap of retained precision
ax5 = fig.add_subplot(2, 3, 5)
attrs = ["name/email/phone"] + QI
M = np.zeros((len(vendors), len(attrs)))
for i, v in enumerate(vendors):
mode = CONTRACTS[v]["id_mode"]
M[i, 0] = {"raw": 1.0, "pseudonym": 0.5, "drop": 0.0}[mode]
for j, c in enumerate(QI):
M[i, j + 1] = 1 - results[v]["best"][c] / (LEVELS[c] - 1)
im = ax5.imshow(M, cmap="RdYlGn_r", vmin=0, vmax=1, aspect="auto")
for i in range(M.shape[0]):
for j in range(M.shape[1]):
ax5.text(j, i, f"{M[i, j]:.2f}", ha="center", va="center", fontsize=10)
ax5.set_xticks(range(len(attrs)))
ax5.set_xticklabels(attrs, rotation=30, ha="right")
ax5.set_yticks(range(len(vendors)))
ax5.set_yticklabels(short)
ax5.set_title("(5) Retained precision per vendor (0 = removed)")
fig.colorbar(im, ax=ax5, fraction=0.046)

# (6) 3D scatter: utility / disclosure / risk for all vendors
ax6 = fig.add_subplot(2, 3, 6, projection="3d")
for v, c, s in zip(vendors, colors, short):
t = tables[v]
f = t[t.precision_ok]
ax6.scatter(f["utility"], f["disclosure"], np.log10(f["raw_risk"]), s=14, c=c, alpha=0.5, label=s)
bb = results[v]["best"]
ax6.scatter([bb["utility"]], [bb["disclosure"]], [np.log10(bb["raw_risk"])],
s=220, c=c, marker="*", edgecolor="k")
ax6.set_xlabel("Contract utility U")
ax6.set_ylabel("Disclosure D")
ax6.set_zlabel("log10 mean risk")
ax6.set_title("(6) Granularity-compliant candidates (stars = selected)")
ax6.legend()

plt.tight_layout()
plt.show()

Code Walkthrough

1. Synthetic customer master table

np.random.default_rng(42) makes the run reproducible. Ages follow a clipped normal distribution, income a log-normal and purchase totals a gamma distribution, which gives realistic long tails. Those tails are exactly the records that end up in small, risky equivalence classes. ZIP codes are built from 25 three-digit prefixes plus two random digits, so coarsening ZIP has a real effect. The three boolean flags stand for consent and business purpose. They drive row-level minimization: a vendor never sees a customer who has not consented to that use.

2. Generalization hierarchies

generalize(col, values, level) maps raw values to their generalized form with vectorized NumPy arithmetic only:

  • Banding is integer floor division followed by multiplication: (v // w) * w.
  • ZIP truncation is v // 10**d.
  • The last level of each hierarchy returns a constant array, which means the column is effectively removed.

label_value turns the generalized numbers into readable labels such as 40-59, 102** or 100000-149999 for the actual vendor file. It returns None for suppressed columns, so they never appear in the release.

SENSITIVITY holds the weights $w_j$: income (2.0) and ZIP (1.5) are treated as most sensitive, gender (0.5) as least sensitive.

3. Vendor contracts

Each contract is a plain dictionary, so legal and compliance staff can review it without reading the algorithm:

  • row_filter: the consent or purpose column that decides which rows the vendor may receive.
  • max_level: the required attributes and the coarsest level each one may be generalized to. Any attribute missing from this dictionary is not required, so the optimizer is free to remove it.
  • k and supp: the $k$-anonymity threshold and the share of records that may be suppressed.
  • id_mode: whether direct identifiers are dropped or replaced with pseudonyms.

4. Equivalence-class computation (naive vs fast)

  • class_sizes_naive is the textbook implementation: build a new DataFrame, run groupby on all QIs and broadcast the group size back to each row.
  • build_codes runs once per dataset. For every attribute and level it stores a dense integer code array, so no generalization work is repeated inside the lattice loop.
  • class_sizes_fast folds the five code arrays into one int64 key with the mixed-radix formula above. One np.unique(..., return_counts=True) then returns all class sizes, and cnt[inv] maps each count back to its record.
  • evaluate derives the contract metrics: records that must be suppressed, $k_{\min}$ after suppression, the mean risk $\bar{R}$ over released records, the pre-suppression risk raw_risk (used for the plots), and whether the suppression limit is met.

5. Performance check

Both methods run on the same 40 lattice nodes. The script reports the time per node and the speed-up, and an assert confirms the two methods give identical class sizes. You get the faster code with a built-in correctness check.

6. Lattice search and release construction

For each vendor:

  1. Apply the row filter (purpose limitation).
  2. Pre-encode the filtered data.
  3. Evaluate all 640 nodes and record $D$, $U_v$, $\bar{R}$, $J$, and whether the node passes the precision limits and the $k$/suppression limits.
  4. Sort the feasible nodes by $J = D + \lambda\bar{R}$ and take the best.
  5. Build the actual release. Add an HMAC pseudonym if the contract allows one, emit only the columns that were not suppressed, and drop the records in classes smaller than $k$.

The HMAC key is derived per vendor, so the same customer gets a different token at each vendor. That blocks cross-vendor linkage while still letting the fraud vendor track a customer across its own submissions.

full_cells is the “export everything” baseline: 60,000 rows × 8 content columns. min_cells is the size of the minimized file.

7. Visualization

plt.figure(figsize=(21, 13)) with add_subplot(2, 3, k) produces one figure with six panels in two rows of three. Two of the panels are 3D (projection="3d").


Execution Results

=== Performance ===
Lattice nodes                : 640
Naive groupby per node       :    32.59 ms
Fast integer-key per node    :     5.83 ms
Speed-up                     :      5.6x
Estimated full-lattice naive :    20.86 s

=== Minimized releases ===

[Marketing Analytics]  k>=10, identifiers=drop
  levels  : {'age': 2, 'zip': 2, 'gender': 0, 'income': 3, 'purchase_total': 2}
  rows    : 60000 -> 37250 (purpose filter) -> 35445 (after suppression)
  columns : 8 -> 4  ['age', 'zip', 'gender', 'purchase_total']
  cells   : 480,000 -> 141,780 (70.5% reduction)
  k_min=10, mean re-id risk=0.0175, max risk=0.1000, suppressed=4.85%
  raw-QI mean re-id risk=1.0000
  sample:
  age   zip  gender purchase_total
50-59 102**       1          0-500
50-59 110**       1          0-500
20-29 102**       0          0-500

[Fraud Scoring]  k>=3, identifiers=pseudonym
  levels  : {'age': 4, 'zip': 1, 'gender': 1, 'income': 3, 'purchase_total': 2}
  rows    : 60000 -> 21149 (purpose filter) -> 20897 (after suppression)
  columns : 8 -> 3  ['token', 'zip', 'purchase_total']
  cells   : 480,000 -> 62,691 (86.9% reduction)
  k_min=3, mean re-id risk=0.0273, max risk=0.3333, suppressed=1.19%
  raw-QI mean re-id risk=1.0000
  sample:
           token   zip purchase_total
f13a38a4aedca985 1020*          0-500
844389cf91ac3c23 1193*          0-500
469545886617eb34 1101*          0-500

[Academic Research]  k>=25, identifiers=drop
  levels  : {'age': 3, 'zip': 3, 'gender': 1, 'income': 2, 'purchase_total': 3}
  rows    : 60000 -> 29017 (purpose filter) -> 28900 (after suppression)
  columns : 8 -> 2  ['age', 'income']
  cells   : 480,000 -> 57,800 (88.0% reduction)
  k_min=36, mean re-id risk=0.0007, max risk=0.0278, suppressed=0.40%
  raw-QI mean re-id risk=1.0000
  sample:
  age        income
40-59 100000-149999
20-39       0-49999
20-39       0-49999


Interpreting the Results

Console output

The performance section shows that the integer-key method is several times faster per lattice node than the pandas groupby version. Exact timings depend on the runtime. The search evaluates $3 \times 640 = 1{,}920$ nodes in total. At this data size the naive version still finishes in seconds, but the gap widens with larger tables, more QIs and deeper hierarchies, where lattices quickly reach tens of thousands of nodes.

The minimized-release section shows how much less each vendor receives:

Vendor Rows Columns Cells shared $k_{\min}$ Suppressed
Marketing Analytics 60,000 → 37,250 → 35,445 8 → 4 −70.5% 10 4.85%
Fraud Scoring 60,000 → 21,149 → 20,897 8 → 3 (token + 2) −86.9% 3 1.19%
Academic Research 60,000 → 29,017 → 28,900 8 → 2 −88.0% 36 0.40%

On the raw quasi-identifiers the mean re-identification risk is $\bar{R} = 1.0$: every customer is unique on age + 5-digit ZIP + gender + exact income + exact purchase. After minimization, risk falls to about 0.0175 for Marketing, about 0.027 for Fraud and about 0.0007 for Research. Each contract’s $k$ bound also limits the worst-case risk to at most $1/k$.

Some details to note:

  • Marketing keeps gender at full precision because the contract requires it. That forces age into 10-year bands and ZIP to 3 digits. Income, which the contract does not require, is removed even though it is the most sensitive attribute.
  • Fraud Scoring receives only a vendor-specific token, a 4-digit ZIP and a $500 purchase band. Age, gender and income are removed because the contract does not need them.
  • Research needs only age and income bands. Gender is optional under its contract, so the optimizer drops it. With such a high $k$ (25), every extra attribute would cost suppressed records.

Graph (1): Data volume

The grey bars show the full export (480,000 cells per vendor) and the colored bars show the minimized release. The labels give a 70–88% reduction. This is the most direct measure of data minimization: every cell that is not shared cannot leak.

Graph (2): Lattice search for Marketing Analytics

Each dot is one of the 640 candidate releases, plotted as disclosure score $D$ against pre-suppression mean risk (log scale). The two quantities rise together: the more precision you share, the more unique each record becomes.

  • Grey nodes are too coarse; they fail the contract’s precision requirement.
  • Orange nodes keep enough precision but fail $k$-anonymity within the 5% suppression budget.
  • The red star is the only release that meets both: the minimum-disclosure release that is still useful under the contract.

Graph (3): 3D risk surface

With gender, income and purchase fixed at the chosen levels, the surface shows $\log_{10}\bar{R}$ as age generalization (x-axis) and ZIP generalization (y-axis) vary. Risk falls steadily as either attribute is coarsened, and the two attributes partly substitute for each other. The red star marks the corner the contract allows: the finest age and ZIP precision the vendor needs, made acceptable by the $k = 10$ requirement and the suppression budget.

Graph (4): Equivalence-class sizes

On log-log axes, the grey bar at size 1 shows the raw data: almost every record is in a class of one, so it is uniquely identifiable. After minimization, the class-size distributions shift to the right. Marketing and Fraud classes cluster around tens to hundreds of records. Research classes run into the thousands because it receives only two coarse attributes. No released record falls below its contract’s $k$.

Graph (5): Retained-precision heatmap

Rows are vendors and columns are attributes. Each cell is the share of precision kept: 1.00 means raw, 0.00 means removed, and 0.50 for identifiers means pseudonymized. The heatmap makes a good summary of the outcome for a data protection impact assessment (DPIA) or a vendor audit. Most of it is green (removed), with red or orange only where a contract needs precision: gender for Marketing, ZIP and the pseudonym for Fraud.

Graph (6): 3D utility–disclosure–risk space

Every candidate that meets a vendor’s precision requirements is plotted by contract utility $U_v$, disclosure $D$ and $\log_{10}$ risk. Within each vendor’s cloud, higher disclosure brings higher risk. The selected releases (stars) sit at the low-disclosure, low-risk edge of their clouds. Research sits furthest toward the low-risk corner because its contract asks for the least information and sets the highest $k$.


Takeaways

  • Data minimization can be computed. Once contract requirements are written as precision limits, a $k$-anonymity threshold and a suppression budget, finding the minimal release becomes a constrained search over a generalization lattice.
  • Minimize on three axes: rows (purpose and consent filters), columns (drop anything not required) and precision (generalize to the coarsest acceptable level).
  • Pseudonymize per vendor. Keyed HMAC tokens with a different key for each vendor let a vendor link its own records without letting vendors link to each other.
  • Optimize the hot loop. Pre-encoding attributes and computing class sizes from a single integer key per node gives the same answer as groupby in a fraction of the time, which matters once the lattice or dataset grows.
  • Use the outputs as audit evidence. The disclosure score, $k_{\min}$, suppression rate and retained-precision heatmap show that each third-party release is limited to what the contract needs.

Optimizing Alert Thresholds for Employee Access-Log Monitoring

Catching Data Leaks Early Without Drowning the SOC

Every security team that monitors employee access logs faces the same tension. If the alert threshold is too low, analysts drown in false positives and start ignoring the queue. If it is too high, a malicious insider quietly walks out with customer data for weeks. In this article we treat that tension as an explicit optimization problem and solve it with Python.

We build a probabilistic model of daily activity scores, add a realistic analyst-capacity constraint, and search for the threshold that minimizes the total expected cost, which combines triage effort, staffing, and leaked records. We also jointly optimize the threshold and the analyst capacity, and we study how the optimal threshold shifts when attackers become stealthier or leaked records become more expensive.


1. Problem Setup

A company has $N = 2000$ employees. Each employee-day is summarized by a single anomaly score $s$ (for example, a standardized combination of download volume, off-hours access, and the number of distinct repositories touched). An alert fires when $s > \tau$.

Normal behavior is a two-component Gaussian mixture. Most employees are ordinary, and a minority are “heavy users” such as data scientists and auditors:

$$
f_0(s) = \sum_{k=1}^{2} w_k , \mathcal{N}(s;, \mu_k, \sigma_k^2), \qquad w = (0.92,, 0.08),\quad \mu = (0.0,, 1.6),\quad \sigma = (1.0,, 1.3)
$$

Exfiltration behavior is shifted upward:

$$
f_1(s) = \mathcal{N}(s;, \mu_{\text{leak}},, \sigma_{\text{leak}}^2), \qquad \mu_{\text{leak}} = 2.8,\quad \sigma_{\text{leak}} = 1.2
$$

There are $M = 3$ insiders leaking simultaneously over a horizon of $H = 30$ days, each exfiltrating $R = 500$ records per day until caught.

Error rates

With $Q(x) = 1 - \Phi(x)$ denoting the Gaussian survival function, the false positive rate and the per-day detection probability are

$$
\alpha(\tau) = \sum_{k} w_k , Q!\left(\frac{\tau - \mu_k}{\sigma_k}\right), \qquad
\beta(\tau) = Q!\left(\frac{\tau - \mu_{\text{leak}}}{\sigma_{\text{leak}}}\right)
$$

The false negative rate is $1 - \beta(\tau)$.

Analyst capacity

Analysts can review at most $K$ alerts per day. The expected daily alert volume is

$$
A(\tau) = N,\alpha(\tau) + M,\beta(\tau)
$$

When $A(\tau) > K$, only a fraction of alerts gets reviewed, so the effective daily detection probability of a leaker drops:

$$
\eta(\tau) = \min!\left(1,\ \frac{K}{A(\tau)}\right), \qquad p_{\text{eff}}(\tau) = \beta(\tau),\eta(\tau)
$$

This is the mechanism behind alert fatigue: lowering the threshold increases $\beta$, but beyond a point it floods the queue and reduces real detections.

Early-detection metrics

The detection day of one leaker is geometric with parameter $p_{\text{eff}}$. The probability of catching the leak within $d$ days, and the expected number of leaking days (truncated at the horizon), are

$$
P_d(\tau) = 1 - \bigl(1 - p_{\text{eff}}\bigr)^{d}, \qquad
\mathbb{E}\bigl[\min(T, H)\bigr] = \frac{1 - (1 - p_{\text{eff}})^{H}}{p_{\text{eff}}}
$$

Cost function

The total expected cost over the horizon combines triage cost, standing analyst capacity, and leakage damage:

with $c_{\text{fp}} = 25$ USD per reviewed alert, $c_{\text{slot}} = 10$ USD per capacity slot per day, and $c_{\text{rec}} = 20$ USD per leaked record.

The optimization problems are

$$
\tau^{\ast} = \arg\min_{\tau}, J(\tau, K_0) \quad (K_0 = 40), \qquad
(\tau^{\ast\ast}, K^{\ast\ast}) = \arg\min_{\tau,,K}, J(\tau, K)
$$


2. Full Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

plt.style.use("dark_background")
plt.rcParams.update({
"figure.facecolor": "#0d1117",
"axes.facecolor": "#161b22",
"savefig.facecolor": "#0d1117",
"axes.grid": True,
"grid.alpha": 0.25,
"font.size": 10,
})

rng = np.random.default_rng(42)

# ------------------------------------------------------------------
# Problem parameters
# ------------------------------------------------------------------
N = 2000 # employees
M = 3 # simultaneous insiders
H = 30 # horizon (days)
K0 = 40 # baseline analyst capacity (alerts reviewed per day)
R = 500 # records leaked per day per insider
C_REC0 = 20.0 # USD per leaked record
C_FP = 25.0 # USD per reviewed alert
C_SLOT = 10.0 # USD per capacity slot per day
MU_LEAK0 = 2.8
SD_LEAK = 1.2

W = np.array([0.92, 0.08])
MU_N = np.array([0.0, 1.6])
SD_N = np.array([1.0, 1.3])


# ------------------------------------------------------------------
# Probability model
# ------------------------------------------------------------------
def pdf_normal(x):
x = np.asarray(x, dtype=float)
return sum(w * norm.pdf(x, loc=m, scale=s) for w, m, s in zip(W, MU_N, SD_N))


def fpr(tau):
tau = np.asarray(tau, dtype=float)
return sum(w * norm.sf(tau, loc=m, scale=s) for w, m, s in zip(W, MU_N, SD_N))


def tpr(tau, mu_leak=MU_LEAK0):
tau = np.asarray(tau, dtype=float)
return norm.sf(tau, loc=mu_leak, scale=SD_LEAK)


def evaluate(tau, K=K0, mu_leak=MU_LEAK0, c_rec=C_REC0):
"""Vectorized evaluation of all metrics (supports numpy broadcasting)."""
a = fpr(tau)
p = tpr(tau, mu_leak)
fp_alerts = N * a
alerts = fp_alerts + M * p
load = np.minimum(1.0, K / np.maximum(alerts, 1e-12))
p_eff = np.clip(p * load, 1e-9, 1.0 - 1e-12)
log_surv = np.log1p(-p_eff)
days = -np.expm1(H * log_surv) / p_eff
pe7 = -np.expm1(7.0 * log_surv)
triage = C_FP * np.minimum(fp_alerts, K) * H
staff = C_SLOT * K * H
leak = M * c_rec * R * days
total = triage + staff + leak
return {"fpr": a, "tpr": p, "alerts": alerts, "pe7": pe7, "days": days,
"triage": triage, "staff": staff, "leak": leak, "total": total}


# ------------------------------------------------------------------
# 1) Optimal threshold for the baseline capacity
# ------------------------------------------------------------------
taus = np.linspace(0.0, 5.5, 2201)
res = evaluate(taus)
i_star = int(np.argmin(res["total"]))
tau_star = float(taus[i_star])

# ------------------------------------------------------------------
# 2) Joint optimization of threshold and capacity
# ------------------------------------------------------------------
t_g = np.linspace(0.5, 4.5, 161)
k_g = np.linspace(5.0, 150.0, 146)
TT, KK = np.meshgrid(t_g, k_g)
Z_raw = evaluate(TT, K=KK)["total"] / 1e3
j_idx = np.unravel_index(int(np.argmin(Z_raw)), Z_raw.shape)
tau_joint, K_joint, J_joint = float(TT[j_idx]), float(KK[j_idx]), float(Z_raw[j_idx])
Z_plot = np.minimum(Z_raw, 400.0)

# ------------------------------------------------------------------
# 3) Sensitivity: optimal threshold vs attacker stealth and record value
# ------------------------------------------------------------------
mu_g = np.linspace(1.8, 4.0, 23)
c_g = np.linspace(5.0, 80.0, 23)
tg = np.linspace(0.0, 5.5, 551)
r_map = evaluate(tg[None, None, :], K=K0,
mu_leak=mu_g[:, None, None], c_rec=c_g[None, :, None])
tau_map = tg[np.argmin(r_map["total"], axis=2)]
MUG, CG = np.meshgrid(mu_g, c_g, indexing="ij")

# ------------------------------------------------------------------
# 4) Monte Carlo validation of the analytic cost
# ------------------------------------------------------------------
def monte_carlo(tau, K=K0, n=20000):
a = float(fpr(tau))
p = float(tpr(tau))
alerts = N * a + M * p
load = min(1.0, K / max(alerts, 1e-12))
pe = min(max(p * load, 1e-9), 1.0 - 1e-12)
fp_daily = rng.binomial(N, a, size=(n, H))
triage = C_FP * np.minimum(fp_daily, K).sum(axis=1)
t_det = np.minimum(rng.geometric(pe, size=(n, M)), H)
leak = C_REC0 * R * t_det.sum(axis=1)
total = triage + leak + C_SLOT * K * H
return float(total.mean()), float(total.std())


# ------------------------------------------------------------------
# Console report
# ------------------------------------------------------------------
print("=" * 78)
print("Threshold comparison (baseline capacity K = %d alerts/day)" % K0)
print("=" * 78)
print("%-16s %6s %8s %8s %10s %9s %12s %11s" %
("Strategy", "tau", "FPR[%]", "TPR[%]", "Alerts/day", "P(7d)[%]", "Leaked/ins.", "Cost[kUSD]"))
for name, t in [("Fixed tau=2.0", 2.0), ("Fixed tau=3.0", 3.0), ("Optimized tau*", tau_star)]:
r = evaluate(t)
print("%-16s %6.2f %8.3f %8.2f %10.1f %9.2f %12.0f %11.1f" % (
name, t, 100 * float(r["fpr"]), 100 * float(r["tpr"]), float(r["alerts"]),
100 * float(r["pe7"]), R * float(r["days"]), float(r["total"]) / 1e3))

print()
print("Optimal threshold (K = %d): tau* = %.3f" % (K0, tau_star))
print("Joint optimum (threshold, capacity): tau** = %.3f, K** = %.0f alerts/day, cost = %.1f kUSD"
% (tau_joint, K_joint, J_joint))

mc_mean, mc_std = monte_carlo(tau_star)
print()
print("Validation at tau*: analytic cost = %.1f kUSD | Monte Carlo mean = %.1f kUSD (std = %.1f kUSD)"
% (float(res["total"][i_star]) / 1e3, mc_mean / 1e3, mc_std / 1e3))

# ------------------------------------------------------------------
# Visualization: 2 rows x 3 columns in a single figure
# ------------------------------------------------------------------
fig = plt.figure(figsize=(22, 12.5))
fig.suptitle("Threshold Optimization for Employee Access-Log Monitoring", fontsize=18, y=0.97)

BLUE, RED, GREEN, GOLD, PINK = "#58a6ff", "#ff7b72", "#3fb950", "#e3b341", "#f778ba"

# (1) Score distributions
ax1 = fig.add_subplot(2, 3, 1)
x = np.linspace(-4, 9, 1200)
f0 = pdf_normal(x)
f1 = norm.pdf(x, loc=MU_LEAK0, scale=SD_LEAK)
ax1.plot(x, f0, color=BLUE, lw=2, label="Normal activity")
ax1.plot(x, f1, color=RED, lw=2, label="Exfiltration activity")
ax1.fill_between(x, f0, where=(x >= tau_star), color=BLUE, alpha=0.45, label="False positives")
ax1.fill_between(x, f1, where=(x < tau_star), color=RED, alpha=0.45, label="Missed detections")
ax1.axvline(tau_star, color=GOLD, ls="--", lw=2, label=r"$\tau^{*}$ = %.2f" % tau_star)
ax1.set_xlabel("Anomaly score $s$")
ax1.set_ylabel("Density")
ax1.set_title("Score distributions and the optimal threshold")
ax1.legend(fontsize=8)

# (2) ROC curve
ax2 = fig.add_subplot(2, 3, 2)
ax2.plot(res["fpr"], res["tpr"], color=GREEN, lw=2)
for name, t, col, mk in [("tau=2.0", 2.0, PINK, "s"), ("tau=3.0", 3.0, BLUE, "^"),
("tau*", tau_star, GOLD, "*")]:
ax2.scatter([float(fpr(t))], [float(tpr(t))], color=col, marker=mk,
s=220 if mk == "*" else 90, zorder=5, label="%s (%.2f)" % (name, t))
ax2.set_xscale("log")
ax2.set_xlim(1e-4, 1.0)
ax2.set_ylim(0.0, 1.02)
ax2.set_xlabel("False positive rate (log scale)")
ax2.set_ylabel("Per-day detection probability $\\beta$")
ax2.set_title("ROC curve with operating points")
ax2.legend(fontsize=8, loc="lower right")

# (3) 3D cost surface over (tau, K)
ax3 = fig.add_subplot(2, 3, 3, projection="3d")
surf = ax3.plot_surface(TT, KK, Z_plot, cmap="viridis", linewidth=0, antialiased=True, alpha=0.92)
ax3.scatter([tau_joint], [K_joint], [min(J_joint, 400.0)], color=RED, s=120,
depthshade=False, label="Joint optimum")
ax3.set_xlabel(r"Threshold $\tau$")
ax3.set_ylabel("Capacity $K$ (alerts/day)")
ax3.set_zlabel("Total cost (kUSD)")
ax3.set_title("Total cost surface (clipped at 400 kUSD)")
ax3.view_init(elev=28, azim=-125)
fig.colorbar(surf, ax=ax3, shrink=0.55, pad=0.08)
ax3.legend(fontsize=8, loc="upper left")

# (4) Cost components vs threshold
ax4 = fig.add_subplot(2, 3, 4)
ax4.plot(taus, res["triage"] / 1e3, color=BLUE, lw=2, label="Triage cost")
ax4.plot(taus, res["leak"] / 1e3, color=RED, lw=2, label="Leakage damage")
ax4.plot(taus, res["total"] / 1e3, color=GOLD, lw=2.5, label="Total cost")
ax4.axvline(tau_star, color="white", ls="--", lw=1.5, label=r"$\tau^{*}$ = %.2f" % tau_star)
ax4.set_xlim(0.5, 5.0)
ax4.set_ylim(0.0, 4.0 * float(res["total"][i_star]) / 1e3)
ax4.set_xlabel(r"Threshold $\tau$")
ax4.set_ylabel("Expected cost over 30 days (kUSD)")
ax4.set_title("Cost trade-off: triage vs leakage")
ax4.legend(fontsize=8)

# (5) Early detection and alert load
ax5 = fig.add_subplot(2, 3, 5)
ax5.plot(taus, 100 * res["pe7"], color=GREEN, lw=2.5, label="P(detect within 7 days)")
ax5.plot(taus, 100 * res["tpr"], color=PINK, lw=1.8, ls=":", label=r"Raw detection rate $\beta$")
ax5.axvline(tau_star, color=GOLD, ls="--", lw=1.5)
ax5.set_xlim(0.0, 5.5)
ax5.set_ylim(0.0, 102.0)
ax5.set_xlabel(r"Threshold $\tau$")
ax5.set_ylabel("Probability (%)")
ax5.set_title("Early detection vs. alert load")
ax5b = ax5.twinx()
ax5b.plot(taus, res["alerts"], color=BLUE, lw=2, label="Expected alerts per day")
ax5b.axhline(K0, color=RED, ls="--", lw=1.5, label="Analyst capacity $K_0$")
ax5b.set_yscale("log")
ax5b.set_ylabel("Alerts per day (log scale)")
ax5b.grid(False)
h1, l1 = ax5.get_legend_handles_labels()
h2, l2 = ax5b.get_legend_handles_labels()
ax5.legend(h1 + h2, l1 + l2, fontsize=8, loc="center right")

# (6) 3D sensitivity surface of the optimal threshold
ax6 = fig.add_subplot(2, 3, 6, projection="3d")
surf2 = ax6.plot_surface(MUG, CG, tau_map, cmap="plasma", linewidth=0, antialiased=True, alpha=0.92)
ax6.set_xlabel(r"Leak intensity $\mu_{\mathrm{leak}}$")
ax6.set_ylabel("Cost per record (USD)")
ax6.set_zlabel(r"Optimal $\tau^{*}$")
ax6.set_title("How the optimal threshold shifts")
ax6.view_init(elev=26, azim=-130)
fig.colorbar(surf2, ax=ax6, shrink=0.55, pad=0.08)

fig.subplots_adjust(left=0.05, right=0.97, top=0.91, bottom=0.07, wspace=0.30, hspace=0.30)
plt.show()

3. Code Walkthrough

Parameters and probability model. The constants at the top encode the scenario. The functions fpr and tpr implement $\alpha(\tau)$ and $\beta(\tau)$ with SciPy’s Gaussian survival function norm.sf, which is numerically more accurate than 1 - norm.cdf in the tails. That matters here because the interesting thresholds live in the far tail of the normal-activity distribution.

The evaluate function. This is the core of the model. It computes, in one vectorized pass:

  1. the expected daily alert volume $A(\tau)$ and the review fraction $\eta(\tau)$,
  2. the effective detection probability $p_{\text{eff}}$,
  3. the expected leaking days $\mathbb{E}[\min(T,H)]$ and the 7-day detection probability,
  4. the three cost components and their sum.

The expression $1-(1-p)^H$ is evaluated as -np.expm1(H * np.log1p(-p_eff)), which stays accurate even when $p_{\text{eff}}$ is tiny, and p_eff is clipped to the open interval $(0,1)$ so no division by zero or log(0) can occur. Because every operation is a NumPy array operation, evaluate accepts scalars, 1D arrays, 2D meshgrids, or 3D broadcast arrays without any change.

Speed. The three heavy computations are the 1D threshold scan (2,201 points), the 2D joint grid (about 23,500 cells), and the 3D sensitivity tensor ($23 \times 23 \times 551 \approx 291{,}000$ evaluations). All of them are single vectorized calls rather than Python loops, so the whole script finishes in a few seconds. The Monte Carlo step is vectorized as well: it draws all $20{,}000 \times 30$ daily false-alarm counts with one binomial call and all detection times with one geometric call.

Joint optimization. np.meshgrid builds a $(\tau, K)$ grid, evaluate is called once on the whole grid, and np.unravel_index(np.argmin(...)) recovers the minimizing cell. The plotted surface is clipped at 400 kUSD so the valley floor stays visible instead of being flattened by extreme values at tiny capacities.

Sensitivity tensor. By reshaping tg, mu_g, and c_g into the axes (1,1,T), (A,1,1), and (1,B,1), NumPy broadcasting evaluates every (leak intensity, record cost, threshold) combination at once. argmin along the threshold axis then yields the optimal $\tau^{*}$ for every scenario.

Monte Carlo validation. Each trial simulates 30 days of binomial false alarms (capped at the capacity $K$ per day) and a geometric detection time for each insider. Averaging the resulting total cost provides an independent check of the closed-form expression.


4. Execution Results

==============================================================================
Threshold comparison (baseline capacity K = 40 alerts/day)
==============================================================================
Strategy            tau   FPR[%]   TPR[%] Alerts/day  P(7d)[%]  Leaked/ins.  Cost[kUSD]
Fixed tau=2.0      2.00    5.126    74.75      104.8     90.48         1752       147.1
Fixed tau=3.0      3.00    1.250    43.38       26.3     98.13         1153        99.9
Optimized tau*     2.75    1.780    51.66       37.1     99.38          968        96.8

Optimal threshold (K = 40):            tau* = 2.750
Joint optimum (threshold, capacity):   tau** = 2.875, K** = 32 alerts/day, cost = 95.1 kUSD

Validation at tau*: analytic cost = 96.8 kUSD | Monte Carlo mean = 96.2 kUSD (std = 23.5 kUSD)


5. Reading the Results

Console report

The comparison table puts three strategies side by side: two fixed thresholds that a team might pick by rule of thumb ($\tau = 2.0$ and $\tau = 3.0$), and the optimized r*. Each row reports the false positive rate, the per-day detection rate, the expected alert volume, the 7-day early-detection probability, the expected number of records leaked per insider, and the total cost. The Monte Carlo line at the bottom compares the simulated mean cost with the analytic value at $\tau^{*}$. Close agreement confirms that the closed-form geometric-delay model is a faithful description of the simulated process.

Panel 1: score distributions

The blue region is the mass of normal behavior that crosses the threshold (false positives), and the red region is the mass of exfiltration behavior that stays below it (missed detections). Moving the dashed line to the right shrinks the blue area and grows the red one. The heavy-user component of the normal mixture creates a fat right tail that overlaps the leak distribution, which is why a naive “three sigma” rule is not obviously the right choice here.

Panel 2: ROC curve

The horizontal axis is logarithmic because practical operating points live at false positive rates of a few percent or less. The curve shows how much extra detection power each additional order of magnitude of false alarms buys. The three markers show that the optimized threshold is not simply the point nearest the top-left corner. It is the point where the marginal cost of one more false alarm equals the marginal saving from earlier detection, subject to the analyst capacity.

Panel 3: 3D cost surface over threshold and capacity

This surface shows the total cost for every combination of threshold and analyst capacity. Two walls are visible. When capacity is too small, the queue saturates, review probability collapses, and the leakage cost explodes. When the threshold is too high, almost nothing fires and leakage dominates regardless of staffing. The valley between those walls is where the joint optimum (red marker) sits. The valley floor is fairly flat in the capacity direction once enough analysts are available, while it is much sharper in the threshold direction, so choosing $\tau$ well matters more than adding more staff beyond the optimum.

Panel 4: cost components

Triage cost falls as the threshold rises, because fewer innocent employees are flagged. Leakage damage rises as the threshold rises, because insiders stay undetected longer. Their sum is a U-shaped curve, and the dashed line marks its minimum. The curve is steeper on the low-threshold side of the minimum, where queue saturation sets in, than on the high-threshold side, which tells us that erring slightly high is cheaper than erring low in this scenario.

Panel 5: early detection and alert load

The green curve is the probability of catching an insider within 7 days, and the dotted pink curve is the raw detection rate $\beta(\tau)$ that would apply if analysts had unlimited capacity. The two curves coincide at high thresholds, where the queue is short. At low thresholds they separate sharply, because the blue alert-volume curve rises above the red capacity line and alert fatigue suppresses real detections. This is the central insight of the study: the early-detection probability is not monotonic in the threshold. Lowering $\tau$ past the point where the alert volume exceeds capacity makes early detection worse, not better.

Panel 6: 3D sensitivity of the optimal threshold

The surface shows how $\tau^{*}$ changes with the attacker’s stealth ($\mu_{\text{leak}}$, the average anomaly score of malicious days) and the cost of each leaked record. Two trends stand out. When leaked records become more expensive, the optimal threshold moves down, because earlier detection is worth more false alarms. When attackers become stealthier (smaller $\mu_{\text{leak}}$), their distribution overlaps the normal one more heavily, and the optimal threshold has to adapt to the shifted overlap rather than staying at a fixed value. A single static threshold therefore cannot be optimal across threat scenarios, which argues for re-estimating the distributions regularly and re-solving the optimization as the business and the threat landscape change.


6. Conclusion

We formulated access-log threshold selection as an expected-cost minimization that couples three effects: the statistical trade-off between false positives and false negatives, the operational limit of analyst capacity, and the geometric delay until an insider is caught. The main takeaways are:

  • Thresholds chosen by rule of thumb are generally not cost-optimal. The optimum depends on the overlap between normal and malicious behavior, the number of analysts, and the value of the data at risk.
  • Alert fatigue is a first-class term in the model. Once the expected alert volume exceeds capacity, lowering the threshold further reduces the early-detection probability.
  • Threshold and capacity should be optimized jointly. The cost surface shows that a well-chosen threshold gets most of the benefit, and extra analysts beyond the valley floor add little.
  • The optimum moves with the threat model. Record value and attacker stealth both shift $\tau^{*}$, so the optimization should be re-run whenever those assumptions change.

The same framework extends naturally to per-role thresholds, time-varying thresholds that follow business cycles, and multi-feature detectors where the single score $s$ is replaced by a learned risk model.

Optimizing Log and Audit Data Retention

Meeting Legal Requirements, Limiting Breach Damage, and Minimizing Storage Cost

Every log you keep is a double-edged asset. It is evidence when you need to investigate an incident or satisfy an auditor, and it is liability if it leaks. It also costs money every month it sits on disk. Keep too little and you violate regulations or lose the evidence you need. Keep too much and you inflate your storage bill and the blast radius of a breach.

In this post we turn that tension into a small optimization problem and solve it in Python. For six log categories we choose two numbers each:

  • the total retention period $R$ (days), and
  • the hot-storage period $h$ (days), the number of days the data stays on fast, expensive storage before moving to cheap archive.

The Model

For a category with monthly volume $v$ (GB/month), the monthly cost is the sum of five terms:

The symbols are:

  • $c_{\text{hot}}, c_{\text{cold}}$: storage price per GB-month for the hot and cold tiers.
  • $p$: annual probability of a breach, and $c_{\text{leak}}$: damage per sensitivity-weighted GB-month of exposed data.
  • $s$: sensitivity weight of the category.
  • $\lambda$: number of investigations or audit requests per month.
  • $C_{\text{miss}}$: cost incurred when the needed evidence has already been deleted.
  • $\theta, k$: scale and shape of a Weibull distribution describing how late a request may arrive.
  • $C_{\text{ret}}$: cost of restoring data from cold storage, and $\ell$: the typical lookback of an investigation (days).

The optimization problem is:

$$
\min_{R,,h}; J(R,h)\quad\text{s.t.}\quad R\ge L_{\text{legal}},\qquad 0\le h\le R
$$

The key insight is that the breach term grows linearly in $R$, while the evidence-missing term decays exponentially. The optimum sits where the marginal breach exposure equals the marginal reduction in expected evidence loss:

$$
\frac{\partial J}{\partial R}=v,c_{\text{cold}}+\frac{p}{12},c_{\text{leak}},s,v-\lambda,C_{\text{miss}},\frac{k}{\theta}\left(\frac{R}{\theta}\right)^{k-1}e^{-(R/\theta)^{k}}=0
$$

When this root lies below the legal minimum $L_{\text{legal}}$, the legal constraint is binding and the best choice is to delete exactly at the legal limit.

The Example

We compare three policies for six log categories:

  1. Naive: keep everything for 7 years (2,555 days), all on hot storage.
  2. Legal minimum: keep each category only for its legal period, on cold storage with a 30-day hot window.
  3. Optimized: the solution of the problem above.
Category Volume (GB/mo) Legal minimum (days) Sensitivity
Auth 40 365 3.0
Payment audit 5 2,555 5.0
Web access 300 90 1.0
DB audit 60 730 4.0
App debug 500 30 0.5
Network flow 800 180 1.5

Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # noqa: F401

np.random.seed(42)
pd.set_option("display.width", 200)
pd.set_option("display.max_columns", 30)

# ---------------- Parameters ----------------
C_HOT, C_COLD = 0.023, 0.004 # USD / GB / month (hot SSD-like, cold archive)
P_YEAR, C_LEAK = 0.10, 2.0 # annual breach probability, damage USD per sensitivity-weighted GB-month
K_WEIB = 0.8 # Weibull shape for "audit request arrives late"

cats = pd.DataFrame({
"name": ["Auth", "Payment audit", "Web access", "DB audit", "App debug", "Network flow"],
"vol": [40.0, 5.0, 300.0, 60.0, 500.0, 800.0], # GB / month
"legal": [365, 2555, 90, 730, 30, 180], # legal minimum retention (days)
"sens": [3.0, 5.0, 1.0, 4.0, 0.5, 1.5], # sensitivity weight
"rate": [0.30, 0.20, 0.25, 0.15, 0.10, 0.20], # investigation/audit events per month
"cmiss": [40000, 150000, 15000, 80000, 5000, 20000], # cost when evidence is missing (USD)
"theta": [150.0, 250.0, 120.0, 300.0, 60.0, 100.0], # Weibull scale (days)
"cret": [2000, 3000, 1500, 2500, 800, 1500], # cost of cold retrieval (USD)
"lookback": [20.0, 30.0, 15.0, 30.0, 7.0, 10.0], # typical lookback of investigations (days)
})

R_GRID = np.arange(1, 3001, 5, dtype=float)
H_GRID = np.arange(0, 401, 5, dtype=float)

# ---------------- Cost model ----------------
def components(v, s, rate, cmiss, theta, cret, lb, R, h, p_year=P_YEAR, c_leak=C_LEAK):
h = np.minimum(h, R)
hot = v * h * C_HOT
cold = v * (R - h) * C_COLD
breach = (p_year / 12.0) * c_leak * s * v * R
miss = rate * cmiss * np.exp(-(R / theta) ** K_WEIB)
retr = rate * cret * np.exp(-h / lb)
return hot, cold, breach, miss, retr

def total(row, R, h, **kw):
return sum(components(row.vol, row.sens, row.rate, row.cmiss, row.theta,
row.cret, row.lookback, R, h, **kw))

def optimize(row, **kw):
RR, HH = np.meshgrid(R_GRID, H_GRID, indexing="ij")
J = total(row, RR, HH, **kw)
J = np.where((RR >= row.legal) & (HH <= RR), J, np.inf)
i, j = np.unravel_index(np.argmin(J), J.shape)
return R_GRID[i], H_GRID[j], J[i, j]

# ---------------- Solve every category ----------------
rows = []
for r in cats.itertuples():
R, h, J = optimize(r)
Jn = total(r, 2555.0, 2555.0)
Jl = total(r, float(r.legal), float(min(r.legal, 30)))
rows.append((r.name, r.legal, R, h, Jn, Jl, J))
res = pd.DataFrame(rows, columns=["category", "legal_min_days", "R_opt_days", "hot_opt_days",
"cost_naive", "cost_legal_min", "cost_opt"])
res["saving_vs_naive_%"] = 100 * (1 - res.cost_opt / res.cost_naive)
res["saving_vs_legal_%"] = 100 * (1 - res.cost_opt / res.cost_legal_min)

print("=== Optimal retention policy per category (monthly cost in USD) ===")
print(res.round(1).to_string(index=False))
print("\n=== Total monthly cost (USD) ===")
print(res[["cost_naive", "cost_legal_min", "cost_opt"]].sum().round(0).to_string())

# ---------------- Data for plots ----------------
a = next(cats.iloc[[0]].itertuples())
RRg, HHg = np.meshgrid(np.arange(365, 1201, 20, dtype=float), np.arange(0, 201, 10, dtype=float), indexing="ij")
Jsurf = total(a, RRg, HHg)

R_line = np.arange(365, 1501, 5, dtype=float)
h_star = res.loc[0, "hot_opt_days"]
comp = components(a.vol, a.sens, a.rate, a.cmiss, a.theta, a.cret, a.lookback, R_line, h_star)
labels = ["Hot storage", "Cold storage", "Breach exposure", "Evidence-missing", "Retrieval"]

pvals = np.linspace(0.02, 0.40, 10)
lvals = np.linspace(0.5, 6.0, 10)
Ropt_map = np.zeros((len(pvals), len(lvals)))
for i, p in enumerate(pvals):
for j, l in enumerate(lvals):
Ropt_map[i, j] = optimize(a, p_year=p, c_leak=l)[0]
PP, LL = np.meshgrid(lvals, pvals)

# ---------------- Plots (2 rows x 3 cols) ----------------
fig = plt.figure(figsize=(21, 12))
fig.suptitle("Log & Audit Data Retention Optimization", fontsize=18, fontweight="bold")

ax = fig.add_subplot(2, 3, 1, projection="3d")
sf = ax.plot_surface(RRg, HHg, Jsurf, cmap="viridis", edgecolor="none", alpha=0.95)
ax.set_xlabel("Retention R (days)"); ax.set_ylabel("Hot period h (days)"); ax.set_zlabel("Cost (USD/month)")
ax.set_title("(1) 3D cost surface: Auth logs")
ax.view_init(elev=28, azim=-125)
fig.colorbar(sf, ax=ax, shrink=0.6, pad=0.1)

ax = fig.add_subplot(2, 3, 2)
ax.stackplot(R_line, *comp, labels=labels)
ax.axvline(365, color="k", ls="--", lw=1.2, label="Legal minimum")
ax.axvline(res.loc[0, "R_opt_days"], color="red", ls="-", lw=1.5, label="Optimal R")
ax.set_xlabel("Retention R (days)"); ax.set_ylabel("Cost (USD/month)")
ax.set_title("(2) Cost components vs retention: Auth logs")
ax.legend(fontsize=8, loc="upper left"); ax.grid(alpha=0.3)

ax = fig.add_subplot(2, 3, 3)
x = np.arange(len(res)); w = 0.27
ax.bar(x - w, res.cost_naive, w, label="Keep everything 7 yrs")
ax.bar(x, res.cost_legal_min, w, label="Legal minimum, cold only")
ax.bar(x + w, res.cost_opt, w, label="Optimized")
ax.set_yscale("log"); ax.set_xticks(x); ax.set_xticklabels(res.category, rotation=25, ha="right")
ax.set_ylabel("Cost (USD/month, log)"); ax.set_title("(3) Policy comparison by category")
ax.legend(fontsize=8); ax.grid(alpha=0.3, axis="y")

ax = fig.add_subplot(2, 3, 4)
ax.bar(x - 0.2, res.legal_min_days, 0.4, label="Legal minimum")
ax.bar(x + 0.2, res.R_opt_days, 0.4, label="Optimal retention")
ax.set_xticks(x); ax.set_xticklabels(res.category, rotation=25, ha="right")
ax.set_ylabel("Days"); ax.set_title("(4) Optimal vs legal retention")
ax.legend(fontsize=8); ax.grid(alpha=0.3, axis="y")

ax = fig.add_subplot(2, 3, 5, projection="3d")
sf2 = ax.plot_surface(PP, LL, Ropt_map, cmap="plasma", edgecolor="none", alpha=0.95)
ax.set_xlabel("Leak damage factor"); ax.set_ylabel("Annual breach prob.")
ax.set_zlabel("Optimal R (days)")
ax.set_title("(5) 3D sensitivity: optimal R (Auth)")
ax.view_init(elev=26, azim=-50)
fig.colorbar(sf2, ax=ax, shrink=0.6, pad=0.1)

ax = fig.add_subplot(2, 3, 6)
bottom = np.zeros(len(res))
parts = [[] for _ in range(5)]
for r, (_, rr) in zip(cats.itertuples(), res.iterrows()):
cmp_ = components(r.vol, r.sens, r.rate, r.cmiss, r.theta, r.cret, r.lookback, rr.R_opt_days, rr.hot_opt_days)
for k in range(5):
parts[k].append(float(cmp_[k]))
for k in range(5):
ax.bar(x, parts[k], bottom=bottom, label=labels[k])
bottom += np.array(parts[k])
ax.set_xticks(x); ax.set_xticklabels(res.category, rotation=25, ha="right")
ax.set_ylabel("Cost (USD/month)"); ax.set_title("(6) Cost breakdown at the optimum")
ax.legend(fontsize=8); ax.grid(alpha=0.3, axis="y")

plt.tight_layout(rect=[0, 0, 1, 0.96])
plt.show()

Code Walkthrough

Parameters. The first block defines unit prices, the breach probability, and the table of six categories. Each row carries the legal minimum, sensitivity, audit frequency, the penalty for missing evidence, and the retrieval penalty. Changing these numbers is all you need to adapt the model to your own environment.

components. This function returns the five cost terms of $J(R,h)$ separately, so we can both sum them for optimization and plot them individually later. It is written with NumPy operations only, so it accepts scalars and whole arrays alike. The line h = np.minimum(h, R) enforces $h \le R$ even when the grid contains infeasible pairs.

optimize. This is where the speed-up happens. Instead of nested Python loops over $(R,h)$, we build the entire grid at once with np.meshgrid (600 values of $R$ times 81 values of $h$, about 48,000 points) and evaluate the cost in a single vectorized call. Infeasible points, those with $R<L_{\text{legal}}$ or $h>R$, are set to $\infty$, and np.argmin plus np.unravel_index locate the global minimum on the grid. Because the cost is evaluated exhaustively, we get the true grid optimum with no risk of a local minimum, in a fraction of a second per category.

Solving and baselines. For every category we compute the optimum, the naive 7-year all-hot cost, and the legal-minimum cost. The final table reports the savings relative to both.

Plot data. We prepare four datasets. The first is a coarse $(R,h)$ surface for the Auth category. The second is a cost curve versus $R$ at the optimal hot period, split into components. The third is a sensitivity map: the optimal $R$ for Auth over a $10\times10$ grid of breach probabilities and leak-damage factors (100 full optimizations, still quick thanks to vectorization). The fourth is the cost breakdown at each category’s optimum.

Figure. A single figure holds six panels in 2 rows by 3 columns. Panels 1 and 5 are 3D surfaces, and the others are 2D charts.

Console Output

=== Optimal retention policy per category (monthly cost in USD) ===
     category  legal_min_days  R_opt_days  hot_opt_days  cost_naive  cost_legal_min  cost_opt  saving_vs_naive_%  saving_vs_legal_%
         Auth             365       616.0          75.0      7461.4          2510.3    1944.5               73.9               22.5
Payment audit            2555      2556.0         160.0      1407.2          1388.1    1183.0               15.9               14.8
   Web access              90       171.0          20.0     30404.5          2474.2    2267.3               92.5                8.4
     DB audit             730       731.0          70.0     13792.6          4832.6    4777.4               65.4                1.1
    App debug              30        31.0           0.0     40028.3           752.6     548.4               98.6               27.1
 Network flow             180       181.0           5.0     98112.0          5454.2    5258.7               94.6                3.6

=== Total monthly cost (USD) ===
cost_naive        191206.0
cost_legal_min     17412.0
cost_opt           15979.0

Result Graphs

Interpreting the Results

Total cost. Keeping everything for seven years on hot storage costs about $191,206 per month across the six categories. Applying only the legal minimum with cold storage brings it down to about $17,412. The optimized policy reaches about $15,979, a 91.6% reduction versus the naive policy and a further 8.2% reduction versus the legal-minimum policy. The first jump comes from tiering and deleting what no one needs. The second comes from tuning each category individually.

Panel 1 (3D cost surface, Auth). The surface has a clear valley. Along the hot-period axis, too little hot time is penalized by retrieval costs, and too much by hot-storage prices. Along the retention axis, cost falls as evidence-loss risk shrinks, then climbs again as storage and breach exposure grow. The optimum is a basin, not a corner.

Panel 2 (cost components, Auth). The legal minimum is 365 days, but the optimum is 616 days. The evidence-missing cost (the area that shrinks as $R$ grows) is large for authentication logs, because investigations of account compromise often arrive late. Extending retention beyond the legal minimum pays off until the rising cold-storage and breach-exposure areas outweigh the shrinking evidence-loss area. The hot period at the optimum is 75 days.

Panel 3 (policy comparison). On a log scale, the optimized bar is always the lowest. The gap to the naive policy is enormous for high-volume, low-risk data such as Network flow (94.6% saving) and App debug (98.6%), because these are exactly the categories where seven years of hot storage is wasteful.

Panel 4 (optimal vs legal retention). For four of the six categories, the optimum is essentially the legal minimum (one grid step above it). In those cases the legal constraint is binding: the marginal cost of keeping data longer exceeds the marginal evidence benefit. Only Auth deviates materially, because its evidence-loss penalty is high relative to its small volume.

Panel 5 (3D sensitivity). Higher breach probability and higher leak damage both push the optimal retention down toward the legal floor, while low risk lets the optimum rise. The surface quantifies a governance question: how much does your risk appetite change how long you should keep authentication logs? When risk estimates are uncertain, this panel shows which direction is safe to err in.

Panel 6 (cost breakdown). At the optimum, the dominant cost differs by category. Voluminous logs are dominated by storage and breach exposure, while the small but critical Payment audit and DB audit logs are dominated by the legal-driven retention itself. This tells you where to spend engineering effort: compress and tier the big categories, and focus on access control and encryption for the sensitive ones.

Takeaways

  1. Legal minimums are floors, not targets. For most categories the best policy is to delete as soon as the law allows. For categories with expensive missing-evidence scenarios, going beyond the minimum can be rational.
  2. Tiering matters as much as retention. The hot period $h$ is a separate lever. App debug logs need no hot window at all, while Payment audit logs justify 160 days.
  3. Risk parameters should be explicit. Breach probability and damage estimates move the optimum, and a sensitivity surface makes that dependence visible and debatable instead of hidden in a policy document.
  4. Vectorized grid search is enough. With two decision variables per category, evaluating the full grid is fast, exact on the grid, and easy to audit, which is a good property for compliance-related decisions.

Balancing Lateral-Movement Risk and Latency with Simulated Annealing

Network Segmentation Design

Flat networks are convenient, and that convenience is what attackers exploit. Once a single laptop or IoT sensor is compromised, nothing stops the intruder from walking toward the database tier. Splitting the network into segments breaks those paths, but every segment boundary adds a firewall hop, extra latency, and more rules to maintain.

This article turns that trade-off into a combinatorial optimization problem and solves it in Python on a concrete 26-host enterprise network.


1. The Example Problem

The network has $n = 26$ hosts with the following roles.

Role Hosts Exposure Asset value
Web 4 high medium
App 5 medium medium-high
DB 4 low critical
Auth (AD/IdP) 2 low critical
Mgmt (jump/admin) 2 low high
Client (workstations) 6 very high low
IoT 3 very high very low

Each host $i$ has an exposure score $e_i$ (how likely it is to be compromised first) and an asset value $v_i$ (how much damage follows if an attacker reaches it). The traffic volume between hosts $i$ and $j$ is $T_{ij}$, and $F_{ij}=\mathbb{1}[T_{ij}>0]$ marks a flow that needs a firewall rule if it crosses a boundary.

The decision variable is a segment assignment $x_i \in {0,\dots,K_{\max}-1}$ for every host. The goal is to choose $x$ so that attackers have few paths, legitimate traffic crosses few boundaries, and the design stays manageable.


2. Mathematical Model

Attack-path weight. The damage potential of a host pair is

$$
S_{ij} = e_i v_j + e_j v_i .
$$

Lateral-movement risk. Hosts in the same segment can reach each other freely, while hosts in different segments are reachable only with a small leak probability $\varepsilon$:

$$
R(x) = \varepsilon \sum_{i<j} S_{ij} + (1-\varepsilon)\sum_{i<j} S_{ij},\mathbb{1}[x_i = x_j].
$$

Latency. Traffic crossing a segment boundary passes through an inspection point and pays a delay $\delta$:

$$
L(x) = \delta \sum_{i<j} T_{ij},\mathbb{1}[x_i \neq x_j].
$$

Operational cost. Each segment costs $c_s$ to run, and each cross-boundary flow needs a rule that costs $c_r$:

$$
O(x) = c_s,K(x) + c_r \sum_{i<j} F_{ij},\mathbb{1}[x_i \neq x_j],
$$

where $K(x)$ is the number of non-empty segments.

Scalarized objective. The three terms are normalized by their worst-case reference values (a flat network for risk, full isolation for latency and operations) and then combined:

$$
J(x) = w_R,\frac{R(x)}{R_{\text{flat}}} + w_L,\frac{L(x)}{L_{\text{all}}} + w_O,\frac{O(x)}{O_{\text{all}}}, \qquad \sum w = 1 .
$$

The constraint is $|{i : x_i = k}| \le M$ for every segment $k$, so no segment grows into a new flat network.

This is a graph-partitioning problem with a non-linear cost and is NP-hard in general, so the code uses simulated annealing with a single-host relocation move. A move is accepted with probability

$$
P_{\text{accept}} = \min!\left(1,; e^{-\Delta J/\tau_t}\right), \qquad \tau_t = \tau_0\left(\frac{\tau_1}{\tau_0}\right)^{t/N}.
$$

Why the incremental update matters. Recomputing $J$ from scratch costs $O(n^2)$ per proposal. Instead, the code keeps three matrices that store, for every host, the sum of $S$, $T$ and $F$ toward each segment:

Moving host $i$ from segment $a$ to segment $b$ then changes the objective components by

which is an $O(1)$ lookup. Only the accepted moves pay an $O(n)$ column update. This is the optimized version used below, and it makes many restarts and parameter sweeps cheap.


3. Full Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import time
from collections import Counter

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from mpl_toolkits.mplot3d import Axes3D # noqa: F401

plt.style.use("dark_background")
plt.rcParams["font.size"] = 8

# ------------------------------------------------------------------
# 1. Synthetic enterprise network
# ------------------------------------------------------------------
SEED = 42
rng = np.random.default_rng(SEED)

ROLES = [("Web", 4), ("App", 5), ("DB", 4), ("Auth", 2),
("Mgmt", 2), ("Client", 6), ("IoT", 3)]
role_id = np.concatenate([np.full(c, r) for r, (_, c) in enumerate(ROLES)])
role_name = np.array([ROLES[r][0] for r in role_id])
n = len(role_id)
host_label = np.array([f"{role_name[i]}{i:02d}" for i in range(n)])

exposure = np.array([0.80, 0.50, 0.20, 0.30, 0.25, 0.90, 0.95])[role_id] * rng.uniform(0.8, 1.2, n)
value = np.array([0.40, 0.60, 1.00, 1.00, 0.90, 0.20, 0.10])[role_id] * rng.uniform(0.8, 1.2, n)

AFF = np.zeros((7, 7))
for (a, b), v in {(0, 1): 6, (1, 2): 8, (0, 0): 1, (1, 1): 2, (2, 2): 3,
(3, 1): 2, (3, 5): 3, (3, 2): 1, (3, 0): 1, (4, 0): 0.8,
(4, 1): 0.8, (4, 2): 0.8, (4, 3): 1.0, (5, 0): 3, (5, 1): 1,
(6, 4): 1.5, (6, 6): 2, (6, 5): 0.5}.items():
AFF[a, b] = AFF[b, a] = v

T = np.zeros((n, n))
for i in range(n):
for j in range(i + 1, n):
a = AFF[role_id[i], role_id[j]]
if a > 0 and rng.random() < min(1.0, a / 3.0):
T[i, j] = T[j, i] = a * rng.exponential(1.0)
F = (T > 0).astype(float)
S = np.outer(exposure, value) + np.outer(value, exposure)
np.fill_diagonal(S, 0.0)

# ------------------------------------------------------------------
# 2. Model parameters
# ------------------------------------------------------------------
EPS, DELTA, C_SEG, C_RULE, MAX_SIZE = 0.05, 0.8, 3.0, 0.5, 8
iu = np.triu_indices(n, 1)
S_u, T_u, F_u = S[iu], T[iu], F[iu]
S_TOT = S_u.sum()
R_FLAT = S_TOT
L_ALL = DELTA * T_u.sum()
O_ALL = C_SEG * n + C_RULE * F_u.sum()


def metrics(x):
same = (x[:, None] == x[None, :])[iu]
risk = EPS * S_TOT + (1 - EPS) * S_u[same].sum()
lat = DELTA * T_u[~same].sum()
ops = C_SEG * len(np.unique(x)) + C_RULE * F_u[~same].sum()
return risk / R_FLAT, lat / L_ALL, ops / O_ALL


def objective(x, w):
r, l, o = metrics(x)
return w[0] * r + w[1] * l + w[2] * o


def anneal(w, kmax, iters=30000, t0=0.05, t1=1e-4, seed=0, record=False):
rg = np.random.default_rng(seed)
if kmax == 1:
x = np.zeros(n, dtype=int)
return x, objective(x, w), None
cap = max(MAX_SIZE, int(np.ceil(n / kmax)))
x = rg.permutation(np.arange(n) % kmax)
onehot = np.eye(kmax)[x]
seg_s, seg_t, seg_f = S @ onehot, T @ onehot, F @ onehot
counts = onehot.sum(axis=0).astype(int)
r_same = 0.5 * seg_s[np.arange(n), x].sum()
t_diff = 0.5 * (T.sum() - (seg_t[np.arange(n), x]).sum())
f_diff = 0.5 * (F.sum() - (seg_f[np.arange(n), x]).sum())
k_used = int((counts > 0).sum())

def cost(rs, td, fd, k):
return (w[0] * (EPS * S_TOT + (1 - EPS) * rs) / R_FLAT
+ w[1] * DELTA * td / L_ALL
+ w[2] * (C_SEG * k + C_RULE * fd) / O_ALL)

cur = cost(r_same, t_diff, f_diff, k_used)
best, best_x = cur, x.copy()
ii = rg.integers(0, n, iters)
bb = rg.integers(0, kmax, iters)
uu = rg.random(iters)
hist_cur, hist_best = [], []
for it in range(iters):
i, b = ii[it], bb[it]
a = x[i]
if b != a and counts[b] < cap:
temp = t0 * (t1 / t0) ** (it / iters)
d_r = seg_s[i, b] - seg_s[i, a]
d_t = seg_t[i, a] - seg_t[i, b]
d_f = seg_f[i, a] - seg_f[i, b]
new_k = k_used - (counts[a] == 1) + (counts[b] == 0)
new = cost(r_same + d_r, t_diff + d_t, f_diff + d_f, new_k)
dj = new - cur
if dj < 0 or uu[it] < np.exp(-dj / temp):
seg_s[:, a] -= S[:, i]
seg_s[:, b] += S[:, i]
seg_t[:, a] -= T[:, i]
seg_t[:, b] += T[:, i]
seg_f[:, a] -= F[:, i]
seg_f[:, b] += F[:, i]
counts[a] -= 1
counts[b] += 1
x[i] = b
r_same += d_r
t_diff += d_t
f_diff += d_f
k_used = int(new_k)
cur = new
if cur < best - 1e-12:
best, best_x = cur, x.copy()
if record and it % 100 == 0:
hist_cur.append(cur)
hist_best.append(best)
hist = (np.array(hist_cur), np.array(hist_best)) if record else None
return best_x, objective(best_x, w), hist


def best_of(w, kmax, restarts=3, iters=30000, record=False):
out = None
for s in range(restarts):
x, j, h = anneal(w, kmax, iters=iters, seed=100 + s, record=record)
if out is None or j < out[1]:
out = (x, j, h)
return out


def relabel(x):
_, inv = np.unique(x, return_inverse=True)
return inv


# ------------------------------------------------------------------
# 3. Solve
# ------------------------------------------------------------------
W = (0.5, 0.3, 0.2)
KMAX = 8
t_start = time.time()
x_opt, j_opt, hist = best_of(W, KMAX, restarts=4, iters=40000, record=True)
x_opt = relabel(x_opt)
t_main = time.time() - t_start

x_flat = np.zeros(n, dtype=int)
x_single = np.arange(n)
x_role = role_id.copy()
x_rand = np.random.default_rng(7).permutation(np.arange(n) % 6)
baselines = [("Flat (no segmentation)", x_flat), ("Per-host isolation", x_single),
("Role-based (7 zones)", x_role), ("Random (6 zones)", x_rand),
("Optimized (SA)", x_opt)]

t_start = time.time()
k_list = list(range(1, 11))
k_res = []
for k in k_list:
xk, jk, _ = best_of(W, k, restarts=3, iters=25000)
k_res.append((k, jk, *metrics(xk)))
k_res = np.array(k_res)

pareto = []
for a in np.linspace(0.05, 0.75, 15):
wp = (a, 0.8 - a, 0.2)
xp, jp, _ = best_of(wp, KMAX, restarts=2, iters=20000)
pareto.append((a, *metrics(xp)))
pareto = np.array(pareto)
t_sweep = time.time() - t_start

# ------------------------------------------------------------------
# 4. Console report
# ------------------------------------------------------------------
print("=" * 72)
print(f"Hosts: {n} | traffic flows: {int(F_u.sum())} | total traffic: {T_u.sum():.1f}")
print(f"Weights (risk, latency, ops) = {W} | cross-segment leak eps = {EPS}")
print("=" * 72)
print(f"{'Design':<26}{'Risk':>8}{'Latency':>10}{'Ops':>8}{'J':>8}{'Zones':>7}{'MaxSize':>9}")
for name, xb in baselines:
r, l, o = metrics(xb)
print(f"{name:<26}{r:8.3f}{l:10.3f}{o:8.3f}{objective(xb, W):8.3f}"
f"{len(np.unique(xb)):7d}{np.bincount(xb).max():9d}")
print("-" * 72)
print("Optimized segments:")
for k in range(x_opt.max() + 1):
members = np.where(x_opt == k)[0]
comp = Counter(role_name[members])
desc = ", ".join(f"{r}x{c}" for r, c in comp.most_common())
print(f" Segment {k}: {len(members):2d} hosts -> {desc}")
print("-" * 72)
r0, l0, o0 = metrics(x_flat)
r1, l1, o1 = metrics(x_opt)
print(f"Risk reduction vs flat : {100 * (1 - r1 / r0):5.1f} %")
print(f"Latency vs per-host isolation: {100 * (1 - l1 / metrics(x_single)[1]):5.1f} % lower")
print(f"Main SA run (4 restarts) : {t_main:5.1f} s")
print(f"K-sweep + Pareto sweep : {t_sweep:5.1f} s")

# ------------------------------------------------------------------
# 5. Visualization (2 rows x 3 columns)
# ------------------------------------------------------------------
fig = plt.figure(figsize=(21, 12))
fig.suptitle("Network Segmentation Design: Risk vs Latency vs Operations", fontsize=16, y=0.98)

ax1 = fig.add_subplot(2, 3, 1)
ax1.plot(hist[0], color="#5dade2", lw=1, alpha=0.7, label="Current J")
ax1.plot(hist[1], color="#f4d03f", lw=2, label="Best J")
ax1.set_xlabel("Iteration (x100)")
ax1.set_ylabel("Objective J")
ax1.set_title("(a) Simulated annealing convergence")
ax1.legend()
ax1.grid(alpha=0.2)

ax2 = fig.add_subplot(2, 3, 2)
order = np.argsort(x_opt, kind="stable")
ax2.imshow(T[np.ix_(order, order)], cmap="magma", interpolation="nearest")
seg_sorted = x_opt[order]
for p in np.where(np.diff(seg_sorted) != 0)[0]:
ax2.axhline(p + 0.5, color="cyan", lw=1.2)
ax2.axvline(p + 0.5, color="cyan", lw=1.2)
ax2.set_xticks(range(n))
ax2.set_yticks(range(n))
ax2.set_xticklabels(host_label[order], rotation=90, fontsize=5)
ax2.set_yticklabels(host_label[order], fontsize=5)
ax2.set_title("(b) Traffic matrix grouped by optimized segments")

ax3 = fig.add_subplot(2, 3, 3, projection="3d")
sc = ax3.scatter(pareto[:, 1], pareto[:, 2], pareto[:, 3], c=pareto[:, 0],
cmap="viridis", s=60, depthshade=False)
r, l, o = metrics(x_opt)
ax3.scatter([r], [l], [o], c="#f4d03f", s=260, marker="*", edgecolors="white",
depthshade=False, label="Chosen design")
ax3.set_xlabel("Risk")
ax3.set_ylabel("Latency")
ax3.set_zlabel("Ops cost")
ax3.set_title("(c) Pareto frontier in 3D")
ax3.legend(loc="upper left", fontsize=8)
fig.colorbar(sc, ax=ax3, shrink=0.55, pad=0.08, label="Risk weight")

ax4 = fig.add_subplot(2, 3, 4, projection="3d")
nseg = x_opt.max() + 1
ang = 2 * np.pi * np.arange(nseg) / nseg
centers = np.stack([4 * np.cos(ang), 4 * np.sin(ang)], axis=1)
pos = np.zeros((n, 3))
cmap = plt.get_cmap("tab10")
for k in range(nseg):
members = np.where(x_opt == k)[0]
for q, i in enumerate(members):
th = 2 * np.pi * q / max(len(members), 1)
pos[i] = [centers[k, 0] + 1.1 * np.cos(th), centers[k, 1] + 1.1 * np.sin(th), value[i] * 3]
thr = np.percentile(T_u[T_u > 0], 55)
for i, j in zip(*iu):
if T[i, j] >= thr:
cross = x_opt[i] != x_opt[j]
ax4.plot([pos[i, 0], pos[j, 0]], [pos[i, 1], pos[j, 1]], [pos[i, 2], pos[j, 2]],
color="#ff4d4d" if cross else "#48c9b0", lw=0.8 if cross else 0.7,
alpha=0.55 if cross else 0.35)
ax4.scatter(pos[:, 0], pos[:, 1], pos[:, 2], c=[cmap(k % 10) for k in x_opt],
s=40 + 120 * exposure, edgecolors="white", depthshade=False)
ax4.set_xlabel("x")
ax4.set_ylabel("y")
ax4.set_zlabel("Asset value")
ax4.set_title("(d) Segmented topology (height = asset value)")
ax4.legend(handles=[Line2D([0], [0], color="#ff4d4d", label="Cross-segment flow"),
Line2D([0], [0], color="#48c9b0", label="Intra-segment flow")],
loc="upper left", fontsize=7)

ax5 = fig.add_subplot(2, 3, 5)
ax5.plot(k_res[:, 0], k_res[:, 2], "o-", color="#e74c3c", label="Risk")
ax5.plot(k_res[:, 0], k_res[:, 3], "s-", color="#5dade2", label="Latency")
ax5.plot(k_res[:, 0], k_res[:, 4], "^-", color="#58d68d", label="Ops cost")
ax5.plot(k_res[:, 0], k_res[:, 1], "D--", color="#f4d03f", lw=2, label="Weighted J")
kb = int(k_res[np.argmin(k_res[:, 1]), 0])
ax5.axvline(kb, color="white", ls=":", alpha=0.6)
ax5.set_xlabel("Maximum number of segments")
ax5.set_ylabel("Normalized value")
ax5.set_title(f"(e) Effect of segment count (best = {kb})")
ax5.legend(fontsize=7)
ax5.grid(alpha=0.2)

ax6 = fig.add_subplot(2, 3, 6)
names = [b[0].split(" (")[0] for b in baselines]
vals = np.array([metrics(b[1]) for b in baselines])
xs = np.arange(len(baselines))
bw = 0.26
ax6.bar(xs - bw, vals[:, 0], bw, color="#e74c3c", label="Risk")
ax6.bar(xs, vals[:, 1], bw, color="#5dade2", label="Latency")
ax6.bar(xs + bw, vals[:, 2], bw, color="#58d68d", label="Ops cost")
ax6.set_xticks(xs)
ax6.set_xticklabels(names, rotation=15, fontsize=7)
ax6.set_ylabel("Normalized value")
ax6.set_title("(f) Design comparison")
ax6.legend(fontsize=7)
ax6.grid(alpha=0.2, axis="y")

fig.subplots_adjust(left=0.05, right=0.97, top=0.92, bottom=0.08, wspace=0.22, hspace=0.3)
plt.show()

4. Code Walkthrough

Section 1: building the network. Hosts are generated by role, and each role has its own exposure and asset-value profile with a little random jitter. Traffic is generated from a role-affinity matrix AFF. Web-to-App and App-to-DB are heavy, Auth talks to many roles at moderate volume, and IoT mostly talks to Mgmt. A pair of hosts gets a flow with probability proportional to its affinity, and the volume is exponentially distributed. This produces the heavy-tailed, role-structured traffic seen in real enterprise networks. The seed is fixed, so the dataset is identical on every run.

Section 2: metrics and normalization. metrics(x) evaluates $R$, $L$ and $O$ with vectorized boolean masks over the upper triangle. Dividing by $R_{\text{flat}}$, $L_{\text{all}}$ and $O_{\text{all}}$ puts all three terms on a comparable scale, so the weights $w$ express policy rather than unit conversion.

Section 3: the annealer. The first half of anneal builds the three segment-sum matrices seg_s, seg_t and seg_f. Each iteration then does the following:

  1. Pick a random host i and a random target segment b.
  2. Skip the move if it would exceed the size cap.
  3. Compute the exact change in each cost component with three array lookups.
  4. Apply the Metropolis rule, and update the matrices only when the move is accepted.

Random numbers are pre-drawn as arrays, which removes Python-level RNG overhead from the loop. Because $\Delta J$ is computed exactly, the final objective(best_x, w) call is a consistency check against the incrementally tracked value. best_of runs several independent restarts and keeps the winner, which guards against unlucky annealing trajectories.

Section 3 (continued): baselines and sweeps. The optimized layout is compared against four reference designs: a flat network, per-host isolation, a role-based layout with one zone per role, and a random layout of six balanced zones. Two sweeps follow. The first changes the maximum allowed number of segments from 1 to 10. The second changes the risk weight $w_R$ from 0.05 to 0.75 while shifting the latency weight, which traces an approximate Pareto frontier.

Section 4: console report. A table compares all designs, followed by the role composition of each optimized segment and the runtime of the experiments.

Section 5: visualization. The six panels are arranged in two rows and three columns. Panels (c) and (d) are 3D plots.


5. Console Output

========================================================================
Hosts: 26 | traffic flows: 131 | total traffic: 463.9
Weights (risk, latency, ops) = (0.5, 0.3, 0.2) | cross-segment leak eps = 0.05
========================================================================
Design                        Risk   Latency     Ops       J  Zones  MaxSize
Flat (no segmentation)       1.000     0.000   0.021   0.504      1       26
Per-host isolation           0.050     1.000   1.000   0.525     26        1
Role-based (7 zones)         0.135     0.945   0.540   0.459      7        6
Random (6 zones)             0.179     0.788   0.509   0.428      6        5
Optimized (SA)               0.238     0.336   0.376   0.295      5        8
------------------------------------------------------------------------
Optimized segments:
  Segment 0:  1 hosts -> Mgmtx1
  Segment 1:  8 hosts -> Clientx5, Authx2, Webx1
  Segment 2:  6 hosts -> Webx3, Appx2, Clientx1
  Segment 3:  7 hosts -> DBx4, Appx3
  Segment 4:  4 hosts -> IoTx3, Mgmtx1
------------------------------------------------------------------------
Risk reduction vs flat      :  76.2 %
Latency vs per-host isolation:  66.4 % lower
Main SA run (4 restarts)    :   3.6 s
K-sweep + Pareto sweep      :  21.0 s

6. Result Image


7. Reading the Results

Design comparison, panel (f) and the console table

The three trivial designs each fail in a different way.

  • Flat network. It has the lowest latency and operating cost, but its risk is normalized to 1.0. Every compromised host has a direct path to every crown jewel.
  • Per-host isolation. It drives risk down to the floor set by the leak probability $\varepsilon$, but latency and operations both hit their maximum. Every flow crosses a firewall, so this design is unmanageable in practice.
  • Role-based zones. This is the textbook design, and its risk is low at about 0.135. However, the traffic in this network is dominated by cross-role flows (Web↔App, App↔DB, Client↔Web), so the role boundaries cut straight through the heaviest communication. Latency is close to the per-host-isolation level at about 0.945.
  • Random zones. Even random assignment lands in a similar region. This shows that the number of zones matters less than which hosts end up together.

The annealed design reaches $J \approx 0.295$, well below every baseline, which sit between roughly 0.43 and 0.53. Risk falls by about 76% relative to the flat network, and latency is about 66% lower than full isolation.

What the optimizer discovered, panel (b) and the segment listing

The optimizer found a layout that mixes roles by traffic affinity.

  • One segment holds the database tier together with three of the App servers. These are the hosts with the heaviest mutual traffic, so keeping them together removes the most expensive boundary crossings.
  • Another segment groups the Web servers with the remaining App and Client hosts that talk to them.
  • A third segment gathers the Clients with the Auth servers, which they query constantly.
  • IoT devices are isolated together with one management host.
  • One management host sits in a segment of its own, acting as a dedicated administrative enclave.

In the heatmap, the bright traffic blocks fall inside the cyan-bordered squares along the diagonal. Heavy flows stay inside segments, and only a thin trickle of low-volume traffic crosses the boundaries. The few remaining bright cells outside the diagonal are the flows that now need firewall rules, and they are exactly the ones the operations term kept to a minimum.

Convergence, panel (a)

The blue curve shows the objective of the current state. It starts high and noisy, because at high temperature $\tau$ the annealer accepts many uphill moves and explores widely. As $\tau$ falls geometrically, the curve calms down and tracks the best-so-far line. The yellow best-so-far curve drops in steps, and each step corresponds to the annealer escaping one basin for a better one. It flattens well before the final iteration, which indicates the schedule is long enough for this problem size.

How many segments? Panel (e)

Going from 1 to 3 segments, risk collapses quickly while latency and operating cost rise only modestly, because the optimizer can place tightly coupled hosts together. Beyond about five segments the curves flatten, and the weighted objective is minimized at five segments. More segments than that bring no benefit, since the extra boundaries would cut high-traffic pairs or add operating cost without reducing risk enough to compensate. The practical rule is that the right number of segments is driven by the traffic structure of the network, not by the number of roles on an org chart.

The Pareto frontier in 3D, panel (c)

Each dot is an optimized design for a different risk weight. Dots with a high risk weight (yellow) sit at low risk but higher latency and operating cost, and dots with a low risk weight (purple) sit at the opposite corner. The gold star marks the chosen design at $w_R = 0.5$. Every point on this surface is a defensible design, and the choice among them is a policy decision about how much latency and operating burden the organization accepts in exchange for containment.

The segmented topology in 3D, panel (d)

Each segment is a cluster on a ring. Node height encodes asset value and node size encodes exposure. The tall nodes (databases and authentication servers) are grouped away from the large nodes (clients and IoT devices). Red lines are the heavy flows that still cross boundaries, and green lines are the heavy flows contained inside a segment. There are far more green lines than red ones, which is the visual signature of a good segmentation: communication is local, and the paths an attacker could use are short and well separated from the high-value assets.


8. Takeaways

  • Segmentation is an optimization problem. Role-based zoning is a reasonable starting point, but traffic-aware assignment can beat it substantially when real communication patterns cut across roles.
  • The $O(1)$ incremental evaluation of the objective is what makes annealing practical, even with multiple restarts and parameter sweeps.
  • The weights $w_R$, $w_L$ and $w_O$ make the policy trade-off explicit. Sweeping them gives decision-makers a frontier of options instead of a single number.
  • The same framework extends naturally to real data. Replace $T$ with measured NetFlow or VPC flow-log volumes, $e_i$ with vulnerability-scan scores, and $v_i$ with business-impact ratings, and the optimizer will propose a segment map ready for review.

Optimizing Encryption Key Management with Python

How Often Should You Rotate, and Where Should Keys Live?

Every security team ends up asking the same two questions about encryption keys:

  1. How often should we rotate them?
  2. 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import time
import itertools
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from mpl_toolkits.mplot3d import Axes3D # noqa: F401
from scipy.optimize import minimize_scalar

rng = np.random.default_rng(42)

# ------------------------------------------------------------
# 1. Problem data
# ------------------------------------------------------------
storages = ["Local file", "Self-hosted vault", "Cloud KMS", "HSM"]
lam = np.array([0.30, 0.08, 0.02, 0.004]) # key compromises per year
F = np.array([0.0, 6000.0, 2400.0, 18000.0]) # fixed cost per year [$]
C_rot = np.array([400.0, 150.0, 40.0, 60.0]) # cost per rotation [$]
delta = np.array([120.0, 45.0, 10.0, 5.0]) # mean detection delay [days]

classes = ["Customer PII", "App logs", "Backups", "Payment tokens"]
D = np.array([20.0, 200.0, 500.0, 5.0]) # data encrypted per day [GB]
L = np.array([200.0, 2.0, 30.0, 5000.0]) # loss per exposed GB [$]

T_MIN, T_MAX = 1.0, 365.0
T_grid = np.linspace(T_MIN, T_MAX, 3641) # 0.1-day resolution

# ------------------------------------------------------------
# 2. Analytical cost model
# ------------------------------------------------------------
def exposure_days(T, d):
"""E[U + min(Delta, T-U)], U~Unif(0,T), Delta~Exp(mean d)."""
T = np.asarray(T, dtype=float)
return T / 2.0 + d - (d ** 2 / T) * (1.0 - np.exp(-T / d))

def variable_cost(T, s, c, lam_scale=1.0):
"""Rotation cost + expected breach loss per year (no fixed cost)."""
rot = 365.0 / T * C_rot[s]
brc = lam[s] * lam_scale * L[c] * D[c] * exposure_days(T, delta[s])
return rot, brc

# Optimal T for every (class, storage) pair: vectorized grid + refinement
n_c, n_s = len(classes), len(storages)
T_star = np.zeros((n_c, n_s))
J_star = np.zeros((n_c, n_s))
for c in range(n_c):
for s in range(n_s):
rot, brc = variable_cost(T_grid, s, c)
k = np.argmin(rot + brc)
lo, hi = T_grid[max(k - 1, 0)], T_grid[min(k + 1, len(T_grid) - 1)]
if hi > lo:
res = minimize_scalar(lambda t: sum(variable_cost(t, s, c)),
bounds=(lo, hi), method="bounded")
T_star[c, s], J_star[c, s] = res.x, res.fun
else:
T_star[c, s], J_star[c, s] = T_grid[k], (rot + brc)[k]

# ------------------------------------------------------------
# 3. Joint assignment (shared fixed cost) by full enumeration
# ------------------------------------------------------------
assign = np.array(list(itertools.product(range(n_s), repeat=n_c))) # (256, 4)
var_part = J_star[np.arange(n_c), assign].sum(axis=1)
used = np.zeros((len(assign), n_s), dtype=bool)
used[np.arange(len(assign))[:, None], assign] = True
fixed_part = (used * F).sum(axis=1)
total = var_part + fixed_part
best = np.argmin(total)
best_assign = assign[best]

print("=== Optimal T* [days] for each (class, storage) ===")
print(f"{'':16s}" + "".join(f"{s:>19s}" for s in storages))
for c in range(n_c):
print(f"{classes[c]:16s}" + "".join(f"{T_star[c, s]:19.1f}" for s in range(n_s)))

print("\n=== Optimal variable cost J* [$/yr] (without fixed cost) ===")
for c in range(n_c):
print(f"{classes[c]:16s}" + "".join(f"{J_star[c, s]:19,.0f}" for s in range(n_s)))

print("\n=== Best joint policy ===")
for c in range(n_c):
s = best_assign[c]
print(f"{classes[c]:16s} -> {storages[s]:18s} rotate every {T_star[c, s]:6.1f} days")
print(f"Fixed cost : ${fixed_part[best]:,.0f}/yr")
print(f"Variable cost: ${var_part[best]:,.0f}/yr")
print(f"Total : ${total[best]:,.0f}/yr")

base_s = np.zeros(n_c, dtype=int) # everything in a local file
base_T = np.full(n_c, 365.0) # yearly rotation
base_cost = F[0] + sum(sum(variable_cost(base_T[c], base_s[c], c)) for c in range(n_c))
print(f"\nBaseline (local file, 365-day rotation): ${base_cost:,.0f}/yr")
print(f"Reduction: {100 * (1 - total[best] / base_cost):.1f}%")

# ------------------------------------------------------------
# 4. Monte Carlo simulation of annual loss
# ------------------------------------------------------------
def simulate_naive(s_vec, T_vec, n_years):
out = np.zeros(n_years)
for y in range(n_years):
loss = 0.0
for c in range(n_c):
s, T = s_vec[c], T_vec[c]
for _ in range(rng.poisson(lam[s])):
u = rng.uniform(0, T)
dly = rng.exponential(delta[s])
loss += L[c] * D[c] * (u + min(dly, T - u))
out[y] = loss
return out

def simulate_fast(s_vec, T_vec, n_years):
out = np.zeros(n_years)
for c in range(n_c):
s, T = s_vec[c], T_vec[c]
k = rng.poisson(lam[s], size=n_years)
m = int(k.sum())
if m == 0:
continue
u = rng.uniform(0, T, size=m)
dly = rng.exponential(delta[s], size=m)
loss = L[c] * D[c] * (u + np.minimum(dly, T - u))
out += np.bincount(np.repeat(np.arange(n_years), k),
weights=loss, minlength=n_years)
return out

opt_T = T_star[np.arange(n_c), best_assign]

t0 = time.perf_counter(); _ = simulate_naive(base_s, base_T, 20_000); t_naive = time.perf_counter() - t0
t0 = time.perf_counter(); _ = simulate_fast(base_s, base_T, 20_000); t_fast = time.perf_counter() - t0
print(f"\nMonte Carlo 20,000 years: loop {t_naive:.3f}s, vectorized {t_fast:.4f}s "
f"(x{t_naive / max(t_fast, 1e-9):.0f} faster)")

N = 500_000
loss_base = simulate_fast(base_s, base_T, N)
loss_opt = simulate_fast(best_assign, opt_T, N)

def risk_stats(x):
v95, v99 = np.quantile(x, [0.95, 0.99])
cvar99 = x[x >= v99].mean()
return x.mean(), v95, v99, cvar99

for name, x in [("Baseline", loss_base), ("Optimized", loss_opt)]:
m, v95, v99, cv = risk_stats(x)
print(f"{name:10s} mean=${m:>12,.0f} VaR95=${v95:>12,.0f} "
f"VaR99=${v99:>12,.0f} CVaR99=${cv:>12,.0f}")

# ------------------------------------------------------------
# 5. Sensitivity data
# ------------------------------------------------------------
c_pii = 0
s_kms = 2
T_s = np.geomspace(1, 365, 120)
scale = np.geomspace(0.1, 10, 100)
TT, SS = np.meshgrid(T_s, scale)
rot3, brc3 = variable_cost(TT, s_kms, c_pii, lam_scale=SS)
Z = np.log10(rot3 + brc3 + F[s_kms])
T_opt_line = T_s[np.argmin(rot3 + brc3, axis=1)]
Z_opt_line = np.log10((rot3 + brc3).min(axis=1) + F[s_kms])

lam_h = np.geomspace(0.001, 1.0, 120)
crot_h = np.geomspace(5, 2000, 120)
LL, CC = np.meshgrid(lam_h, crot_h, indexing="ij")
T_cube = T_grid[::5]
cost_cube = (365.0 / T_cube[None, None, :] * CC[..., None]
+ LL[..., None] * L[c_pii] * D[c_pii]
* exposure_days(T_cube, delta[s_kms])[None, None, :])
T_heat = T_cube[np.argmin(cost_cube, axis=2)]

# ------------------------------------------------------------
# 6. Plots (2 rows x 3 cols)
# ------------------------------------------------------------
fig = plt.figure(figsize=(20, 12))
colors = ["tab:red", "tab:orange", "tab:blue", "tab:green"]

ax1 = fig.add_subplot(2, 3, 1)
for s in range(n_s):
rot, brc = variable_cost(T_grid, s, c_pii)
ax1.plot(T_grid, rot + brc + F[s], color=colors[s], label=storages[s])
ax1.plot(T_star[c_pii, s], J_star[c_pii, s] + F[s], "o", color=colors[s])
ax1.set_xscale("log"); ax1.set_yscale("log")
ax1.set_xlabel("Rotation interval T [days]"); ax1.set_ylabel("Annual cost [$]")
ax1.set_title("Customer PII: total cost vs T (dots = T*)")
ax1.legend(); ax1.grid(True, which="both", alpha=0.3)

ax2 = fig.add_subplot(2, 3, 2)
rot, brc = variable_cost(T_grid, s_kms, c_pii)
ax2.stackplot(T_grid, np.full_like(T_grid, F[s_kms]), rot, brc,
labels=["Fixed", "Rotation", "Expected breach"],
colors=["lightgray", "tab:cyan", "tab:pink"], alpha=0.8)
ax2.axvline(T_star[c_pii, s_kms], color="k", ls="--",
label=f"T* = {T_star[c_pii, s_kms]:.1f} d")
ax2.set_xlim(1, 120); ax2.set_ylim(0, 3 * (J_star[c_pii, s_kms] + F[s_kms]))
ax2.set_xlabel("Rotation interval T [days]"); ax2.set_ylabel("Annual cost [$]")
ax2.set_title("Customer PII in Cloud KMS: cost breakdown")
ax2.legend(loc="upper right"); ax2.grid(alpha=0.3)

ax3 = fig.add_subplot(2, 3, 3, projection="3d")
ax3.plot_surface(np.log10(TT), np.log10(SS), Z, cmap="viridis", alpha=0.85,
linewidth=0, antialiased=True)
ax3.plot(np.log10(T_opt_line), np.log10(scale), Z_opt_line + 0.02,
color="red", lw=3, label="Optimal T*")
ax3.set_xlabel("log10 T [days]"); ax3.set_ylabel("log10 breach-rate scale")
ax3.set_zlabel("log10 annual cost [$]")
ax3.set_title("Cost surface over T and breach rate")
ax3.view_init(elev=28, azim=-130); ax3.legend()

ax4 = fig.add_subplot(2, 3, 4)
bins = np.geomspace(1e2, max(loss_base.max(), loss_opt.max()) * 1.1, 80)
ax4.hist(loss_base[loss_base > 0], bins=bins, alpha=0.6, color="tab:red", label="Baseline")
ax4.hist(loss_opt[loss_opt > 0], bins=bins, alpha=0.6, color="tab:green", label="Optimized")
for x, col in [(loss_base, "tab:red"), (loss_opt, "tab:green")]:
ax4.axvline(np.quantile(x, 0.99), color=col, ls="--")
ax4.set_xscale("log"); ax4.set_yscale("log")
ax4.set_xlabel("Annual breach loss [$] (non-zero years)"); ax4.set_ylabel("Count")
ax4.set_title("Monte Carlo loss distribution (dashed = VaR99)")
ax4.legend(); ax4.grid(alpha=0.3)

ax5 = fig.add_subplot(2, 3, 5)
pc = ax5.pcolormesh(lam_h, crot_h, T_heat.T, shading="auto", cmap="plasma",
norm=LogNorm(vmin=T_heat.min(), vmax=T_heat.max()))
cs = ax5.contour(lam_h, crot_h, T_heat.T, levels=[7, 30, 90, 180], colors="white")
ax5.clabel(cs, fmt="%d d")
ax5.set_xscale("log"); ax5.set_yscale("log")
ax5.set_xlabel("Breach rate λ [1/yr]"); ax5.set_ylabel("Cost per rotation [$]")
ax5.set_title("Optimal T* map (Customer PII, δ = 10 d)")
fig.colorbar(pc, ax=ax5, label="T* [days]")

ax6 = fig.add_subplot(2, 3, 6)
base_each = [sum(variable_cost(base_T[c], base_s[c], c)) for c in range(n_c)]
opt_each = [J_star[c, best_assign[c]] for c in range(n_c)]
x = np.arange(n_c); w = 0.38
ax6.bar(x - w / 2, base_each, w, color="tab:red", label="Baseline")
ax6.bar(x + w / 2, opt_each, w, color="tab:green", label="Optimized")
for i in range(n_c):
ax6.text(x[i] + w / 2, opt_each[i] * 1.15,
f"{storages[best_assign[i]]}\nT*={opt_T[i]:.0f}d",
ha="center", fontsize=8)
ax6.set_yscale("log"); ax6.set_xticks(x); ax6.set_xticklabels(classes, rotation=15)
ax6.set_ylabel("Variable cost [$/yr]")
ax6.set_title(f"Per-class cost (fixed: {fixed_part[best]:,.0f} vs {F[0]:,.0f} USD/yr)")
ax6.legend(); ax6.grid(axis="y", alpha=0.3)

plt.tight_layout()
plt.show()

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. The lam_scale argument 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:

  1. Evaluate $J$ on all 3,641 grid points in one vectorized call and take argmin.
  2. 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 used marks 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_naive is 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_fast produces the same distribution with vectorized NumPy:
    1. Draw all yearly event counts in one call: k = rng.poisson(lam[s], size=n_years).
    2. Draw all m = k.sum() compromise times and detection delays at once.
    3. Compute every event’s loss in one vector expression with np.minimum.
    4. Map each event back to its year with np.repeat(np.arange(n_years), k) and add up the losses per year with np.bincount(..., weights=loss).

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 argmin traces 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 (poisson with size, repeat, bincount) makes simulating hundreds of thousands of years fast enough for quick what-if analysis of tail risk.

Leak-Aware Data Placement

Balancing Breach Probability, Latency, and Cost with Mixed-Integer Programming

Where should each dataset live? Putting everything in the cheapest cloud region is tempting. Putting everything in the on-premises vault feels safe. In practice, every placement decision trades three quantities against each other: expected loss from a breach, access latency for users, and storage cost. This article builds a concrete placement problem, solves it exactly, and visualizes the trade-off surface.

1. The Scenario

A company holds $N = 12$ datasets and can place each one in exactly one of $M = 5$ locations.

Location Annual breach probability $p_j$ Cost (USD/TB-month) Capacity (TB)
On-prem Tokyo 0.006 40 150
On-prem Osaka 0.008 36 150
Cloud Tokyo 0.020 23 400
Cloud Singapore 0.018 21 400
Cloud Oregon 0.025 18 400

Users access the data from three regions: Japan, Southeast Asia, and North America. Each dataset $i$ has a size $s_i$ (TB), a loss $v_i$ (million USD) if it leaks, and an access volume $a_{ik}$ (thousand requests per day) from each user region $k$. Customer PII, payment records, employee HR data, and partner contracts are bound by a data-residency rule and must stay in Japan.

2. Mathematical Formulation

Let $x_{ij}\in{0,1}$ indicate that dataset $i$ is placed at location $j$. The three objectives are linear in $x$:

$$
f_{\text{risk}}(x)=\sum_{i=1}^{N}\sum_{j=1}^{M} p_j, v_i, x_{ij},
$$

$$
f_{\text{lat}}(x)=\frac{1}{\sum_{i,k} a_{ik}}\sum_{i=1}^{N}\sum_{j=1}^{M}\Big(\sum_{k=1}^{K} a_{ik},\ell_{jk}\Big)x_{ij},
$$

$$
f_{\text{cost}}(x)=12\sum_{i=1}^{N}\sum_{j=1}^{M} c_j, s_i, x_{ij},
$$

where $\ell_{jk}$ is the network latency (ms) from user region $k$ to location $j$ and $c_j$ is the monthly price per TB.

The constraints are:

$$
\sum_{j} x_{ij}=1 \quad \forall i, \qquad
\sum_{i} s_i,x_{ij}\le C_j \quad \forall j,
$$

$$
\sum_{i} v_i,x_{ij}\le B \quad \forall j, \qquad
x_{ij}=0 \ \text{ for forbidden pairs (residency)}.
$$

The second line contains the blast-radius cap $B = 160$ million USD. No single location may hold more than $B$ of exposed loss, so one breach can never be catastrophic.

To explore the trade-off, each objective is normalized with an ideal value $f_k^{\ast}$ (its single-objective optimum) and a nadir value $f_k^{\text{nad}}$ (its worst value among the three single-objective optima). The scalarized problem is

$$
\min_{x}\ \sum_{k\in{\text{risk, lat, cost}}} w_k,\frac{f_k(x)-f_k^{\ast}}{f_k^{\text{nad}}-f_k^{\ast}},
\qquad w_k\ge 0,\quad \sum_k w_k=1 .
$$

Sweeping $w$ over the simplex traces out the Pareto front. The resulting problem has only $60$ binary variables, so an exact MILP solver finishes each instance almost instantly. The script builds the constraint matrices once and reuses them for every weight vector, which keeps the whole sweep lightweight.

3. Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import time
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import milp, LinearConstraint, Bounds

plt.style.use("dark_background")
rng = np.random.default_rng(42)

# ------------------------------------------------------------
# 1. Problem data
# ------------------------------------------------------------
datasets = ["Customer PII", "Payment records", "Employee HR", "Source code",
"Product catalog", "Web analytics", "Access logs", "ML training set",
"Backups", "Marketing assets", "Sensor telemetry", "Partner contracts"]
locations = ["On-prem Tokyo", "On-prem Osaka", "Cloud Tokyo",
"Cloud Singapore", "Cloud Oregon"]
regions = ["Japan", "SE Asia", "N. America"]

N, M, K = len(datasets), len(locations), len(regions)

size_tb = np.array([8, 12, 3, 2, 5, 40, 60, 80, 100, 20, 50, 1], dtype=float)
loss_musd = np.array([50, 80, 30, 40, 2, 5, 8, 20, 60, 1, 3, 25], dtype=float)

# thousand requests per day issued from each user region
access = np.array([
[90, 5, 5],
[120, 10, 10],
[20, 0, 0],
[40, 5, 5],
[60, 80, 90],
[50, 70, 60],
[30, 20, 10],
[15, 5, 20],
[2, 1, 1],
[30, 40, 70],
[20, 120, 10],
[8, 2, 4],
], dtype=float)

p_leak = np.array([0.006, 0.008, 0.020, 0.018, 0.025]) # annual breach probability
cost_tb_month = np.array([40.0, 36.0, 23.0, 21.0, 18.0]) # USD per TB-month
capacity_tb = np.array([150.0, 150.0, 400.0, 400.0, 400.0]) # TB per location
blast_cap = 160.0 # max exposed loss per location [M USD]

latency_ms = np.array([
[5, 70, 110],
[10, 75, 115],
[6, 68, 105],
[70, 8, 170],
[100, 165, 25],
], dtype=float) # location x user region

residency_sets = [0, 1, 2, 11] # datasets that must stay in Japan
allowed = np.ones((N, M), dtype=bool)
for i in residency_sets:
allowed[i, 3] = False
allowed[i, 4] = False

# ------------------------------------------------------------
# 2. Linear coefficients of the three objectives
# ------------------------------------------------------------
risk_coef = np.outer(loss_musd, p_leak) * 1000.0 # k USD / year
lat_coef = (access @ latency_ms.T) / access.sum() # mean latency [ms]
cost_coef = np.outer(size_tb, cost_tb_month) * 12.0 / 1000.0 # k USD / year
coefs = np.stack([risk_coef, lat_coef, cost_coef]) # shape (3, N, M)


def evaluate(x):
return (coefs * x[None, :, :]).sum(axis=(1, 2))


# ------------------------------------------------------------
# 3. Exact MILP solver (HiGHS via SciPy)
# ------------------------------------------------------------
A_assign = np.zeros((N, N * M))
A_cap = np.zeros((M, N * M))
A_blast = np.zeros((M, N * M))
for i in range(N):
A_assign[i, i * M:(i + 1) * M] = 1.0
for j in range(M):
A_cap[j, i * M + j] = size_tb[i]
A_blast[j, i * M + j] = loss_musd[i]

base_constraints = [
LinearConstraint(A_assign, 1.0, 1.0),
LinearConstraint(A_cap, -np.inf, capacity_tb),
LinearConstraint(A_blast, -np.inf, np.full(M, blast_cap)),
]
var_bounds = Bounds(np.zeros(N * M), allowed.ravel().astype(float))


def solve_milp(c_matrix):
res = milp(c=c_matrix.ravel(),
constraints=base_constraints,
integrality=np.ones(N * M),
bounds=var_bounds)
if not res.success:
raise RuntimeError("MILP failed: " + str(res.message))
return np.round(res.x).reshape(N, M).astype(int)


# Payoff table: optimise each objective alone
single_solutions = [solve_milp(coefs[k]) for k in range(3)]
payoff = np.array([evaluate(x) for x in single_solutions])
ideal = np.diag(payoff).copy()
nadir = payoff.max(axis=0)
ranges = np.maximum(nadir - ideal, 1e-9)


def norm_coef(w):
return sum(w[k] * coefs[k] / ranges[k] for k in range(3))


def score(F, w):
return float(np.sum(np.asarray(w) * (F - ideal) / ranges))


# ------------------------------------------------------------
# 4. Weighted-sum sweep over the simplex
# ------------------------------------------------------------
t0 = time.perf_counter()
sweep_w, sweep_S, sweep_x = [], [], []
for a in range(11):
for b in range(11 - a):
w = np.array([a / 10.0, b / 10.0, (10 - a - b) / 10.0])
x = solve_milp(norm_coef(w))
sweep_w.append(w)
sweep_S.append(score(evaluate(x), w))
sweep_x.append(x)
sweep_w = np.array(sweep_w)
sweep_S = np.array(sweep_S)
sweep_time = time.perf_counter() - t0

unique = {}
for x in sweep_x:
unique[tuple(x.ravel())] = x
uniq_x = list(unique.values())
uniq_F = np.array([evaluate(x) for x in uniq_x])


def non_dominated(F):
keep = []
for a in range(len(F)):
dom = np.any(np.all(F <= F[a] + 1e-9, axis=1) & np.any(F < F[a] - 1e-9, axis=1))
keep.append(not dom)
return np.array(keep)


mask = non_dominated(uniq_F)
pareto_x = [x for x, m in zip(uniq_x, mask) if m]
pareto_F = uniq_F[mask]

# ------------------------------------------------------------
# 5. Balanced solution, greedy heuristic and random baseline
# ------------------------------------------------------------
w_bal = np.array([1 / 3, 1 / 3, 1 / 3])
x_bal = solve_milp(norm_coef(w_bal))
F_bal = evaluate(x_bal)


def greedy_solution(w):
c = norm_coef(w)
x = np.zeros((N, M), dtype=int)
used_cap = np.zeros(M)
used_blast = np.zeros(M)
for i in np.argsort(-loss_musd):
best_j, best_c = -1, np.inf
for j in range(M):
if not allowed[i, j]:
continue
if used_cap[j] + size_tb[i] > capacity_tb[j] + 1e-9:
continue
if used_blast[j] + loss_musd[i] > blast_cap + 1e-9:
continue
if c[i, j] < best_c:
best_j, best_c = j, c[i, j]
if best_j < 0:
raise RuntimeError("Greedy heuristic found no feasible site.")
x[i, best_j] = 1
used_cap[best_j] += size_tb[i]
used_blast[best_j] += loss_musd[i]
return x


x_greedy = greedy_solution(w_bal)
F_greedy = evaluate(x_greedy)


def is_feasible(x):
cap_ok = np.all((x * size_tb[:, None]).sum(axis=0) <= capacity_tb + 1e-9)
blast_ok = np.all((x * loss_musd[:, None]).sum(axis=0) <= blast_cap + 1e-9)
return bool(cap_ok and blast_ok)


random_x, trials = [], 0
while len(random_x) < 3000 and trials < 100000:
trials += 1
x = np.zeros((N, M), dtype=int)
for i in range(N):
x[i, rng.choice(np.flatnonzero(allowed[i]))] = 1
if is_feasible(x):
random_x.append(x)
random_F = np.array([evaluate(x) for x in random_x])
random_S = ((random_F - ideal) / ranges) @ w_bal

# ------------------------------------------------------------
# 6. Console report
# ------------------------------------------------------------
print("=== Problem size ===")
print(f"datasets: {N}, locations: {M}, binary variables: {N * M}")
print(f"feasible random placements sampled: {len(random_x)} (trials: {trials})")
print()
print("=== Payoff table (rows: optimised objective) ===")
print(f"{'optimised for':<16}{'risk [k$/yr]':>14}{'latency [ms]':>14}{'cost [k$/yr]':>14}")
for name, row in zip(["risk", "latency", "cost"], payoff):
print(f"{name:<16}{row[0]:>14.1f}{row[1]:>14.2f}{row[2]:>14.1f}")
print()
print(f"=== Weighted-sum sweep: {len(sweep_x)} MILPs in {sweep_time:.2f} s, "
f"{len(pareto_x)} Pareto-optimal placements ===")
print()
print("=== Method comparison (balanced weights 1/3, 1/3, 1/3) ===")
print(f"{'method':<22}{'risk':>10}{'latency':>10}{'cost':>10}{'score':>10}")
rows = [
("Random (mean)", random_F.mean(axis=0), float(random_S.mean())),
("Random (best of all)", random_F[np.argmin(random_S)], float(random_S.min())),
("Greedy heuristic", F_greedy, score(F_greedy, w_bal)),
("MILP optimum", F_bal, score(F_bal, w_bal)),
]
for name, F, s in rows:
print(f"{name:<22}{F[0]:>10.1f}{F[1]:>10.2f}{F[2]:>10.1f}{s:>10.4f}")
print()
print("=== Optimal placement (balanced weights) ===")
print(f"{'dataset':<18}{'TB':>6}{'loss [M$]':>11} location")
for i in range(N):
j = int(np.argmax(x_bal[i]))
print(f"{datasets[i]:<18}{size_tb[i]:>6.0f}{loss_musd[i]:>11.0f} {locations[j]}")
print()
print("=== Load per location (balanced weights) ===")
for j in range(M):
tb = float((x_bal[:, j] * size_tb).sum())
ex = float((x_bal[:, j] * loss_musd).sum())
print(f"{locations[j]:<18}{tb:>8.0f} TB exposed loss {ex:>6.0f} M$")

# ------------------------------------------------------------
# 7. Visualisation: 2 rows x 3 columns
# ------------------------------------------------------------
fig = plt.figure(figsize=(22, 12))
fig.suptitle("Leak-aware data placement: risk, latency and cost trade-offs",
fontsize=18, y=0.985)

# (1,1) Risk vs cost, coloured by latency
ax1 = fig.add_subplot(2, 3, 1)
order = np.argsort(pareto_F[:, 0])
sc = ax1.scatter(pareto_F[order, 0], pareto_F[order, 2], c=pareto_F[order, 1],
cmap="plasma", s=80, edgecolor="white", linewidth=0.4)
ax1.plot(pareto_F[order, 0], pareto_F[order, 2], color="white", alpha=0.25)
ax1.scatter([F_bal[0]], [F_bal[2]], marker="*", s=380, color="yellow",
edgecolor="black", zorder=5, label="Balanced optimum")
cb = fig.colorbar(sc, ax=ax1)
cb.set_label("Mean latency [ms]")
ax1.set_xlabel("Expected leak loss [k$/yr]")
ax1.set_ylabel("Storage cost [k$/yr]")
ax1.set_title("Pareto-optimal placements")
ax1.legend(loc="upper right")
ax1.grid(alpha=0.2)

# (1,2) 3D objective space
ax2 = fig.add_subplot(2, 3, 2, projection="3d")
ax2.scatter(random_F[:, 0], random_F[:, 1], random_F[:, 2],
color="gray", alpha=0.35, s=8, label="Random feasible")
ax2.scatter(pareto_F[:, 0], pareto_F[:, 1], pareto_F[:, 2],
color="#00e5ff", s=45, label="Pareto-optimal")
ax2.scatter([F_greedy[0]], [F_greedy[1]], [F_greedy[2]],
color="orange", s=120, marker="D", label="Greedy")
ax2.scatter([F_bal[0]], [F_bal[1]], [F_bal[2]],
color="yellow", s=320, marker="*", label="MILP balanced")
ax2.set_xlabel("Risk [k$/yr]")
ax2.set_ylabel("Latency [ms]")
ax2.set_zlabel("Cost [k$/yr]")
ax2.set_title("Objective space")
ax2.view_init(elev=22, azim=-58)
ax2.legend(loc="upper left", fontsize=8)

# (1,3) Assignment heat map
ax3 = fig.add_subplot(2, 3, 3)
ax3.imshow(x_bal, cmap="viridis", aspect="auto", vmin=0, vmax=1)
ax3.set_xticks(range(M))
ax3.set_xticklabels(locations, rotation=25, ha="right")
ax3.set_yticks(range(N))
ax3.set_yticklabels([f"{datasets[i]} ({size_tb[i]:.0f} TB)" for i in range(N)], fontsize=8)
ax3.set_title("Optimal placement matrix (balanced)")
ax3.set_xticks(np.arange(-0.5, M, 1), minor=True)
ax3.set_yticks(np.arange(-0.5, N, 1), minor=True)
ax3.grid(which="minor", color="black", linewidth=1.0)
ax3.tick_params(which="minor", length=0)

# (2,1) Normalised comparison of methods
ax4 = fig.add_subplot(2, 3, 4)
method_names = ["Random\nmean", "Greedy", "MILP\nbalanced", "Risk-min", "Latency-min", "Cost-min"]
method_F = np.array([random_F.mean(axis=0), F_greedy, F_bal,
payoff[0], payoff[1], payoff[2]])
method_N = (method_F - ideal) / ranges
width = 0.26
pos = np.arange(len(method_names))
for k, (lab, col) in enumerate(zip(["Risk", "Latency", "Cost"],
["#ff5252", "#40c4ff", "#b2ff59"])):
ax4.bar(pos + (k - 1) * width, method_N[:, k], width, label=lab, color=col)
ax4.set_xticks(pos)
ax4.set_xticklabels(method_names, fontsize=9)
ax4.set_ylabel("Normalised regret (0 = best, 1 = worst)")
ax4.set_title("Method comparison")
ax4.legend()
ax4.grid(axis="y", alpha=0.2)

# (2,2) 3D surface of optimal scalarised value over the weight simplex
ax5 = fig.add_subplot(2, 3, 5, projection="3d")
surf = ax5.plot_trisurf(sweep_w[:, 0], sweep_w[:, 1], sweep_S, cmap="viridis",
linewidth=0.2, antialiased=True, alpha=0.95)
ax5.set_xlabel("Risk weight")
ax5.set_ylabel("Latency weight")
ax5.set_zlabel("Optimal score")
ax5.set_title("Optimal score over the weight simplex")
ax5.view_init(elev=28, azim=-125)
fig.colorbar(surf, ax=ax5, shrink=0.6, pad=0.1)

# (2,3) Stacked load per location
ax6 = fig.add_subplot(2, 3, 6)
sol_names = ["Risk-min", "Latency-min", "Cost-min", "Balanced"]
sol_x = [single_solutions[0], single_solutions[1], single_solutions[2], x_bal]
loads = np.array([(x * size_tb[:, None]).sum(axis=0) for x in sol_x])
palette = plt.get_cmap("Set2")(np.linspace(0, 1, M))
bottom = np.zeros(len(sol_names))
for j in range(M):
ax6.bar(sol_names, loads[:, j], bottom=bottom, color=palette[j], label=locations[j])
bottom += loads[:, j]
ax6.set_ylabel("Stored volume [TB]")
ax6.set_title("Where the data ends up")
ax6.legend(fontsize=8, loc="upper right")
ax6.grid(axis="y", alpha=0.2)

fig.subplots_adjust(left=0.05, right=0.97, top=0.92, bottom=0.08, wspace=0.28, hspace=0.38)
plt.show()

4. Code Walkthrough

Section 1: problem data. Every array is indexed by dataset ($i$) or location ($j$). The allowed mask encodes data residency: for the four Japan-only datasets, the Singapore and Oregon columns are switched off. The solver receives this mask as upper bounds of zero on the corresponding variables.

Section 2: linear coefficients. Each objective is a matrix with one entry per pair $(i, j)$, so the total value of a placement is simply the sum of the entries selected by $x$. The risk matrix is the outer product of loss and breach probability. The latency matrix is access @ latency_ms.T, which gives for every dataset–location pair the request-weighted latency, divided by total traffic to yield a mean in milliseconds. The cost matrix is the outer product of size and monthly price, multiplied by 12. The three matrices are stacked into one array so that evaluate returns all objectives in a single vectorized expression.

Section 3: exact MILP. milp from SciPy calls the HiGHS solver. Three constraint blocks are built once: one row per dataset forcing exactly one location, one row per location for capacity, and one row per location for the blast-radius cap. Integrality is set on every variable and the bounds restrict them to ${0,1}$, with forbidden pairs fixed at zero. The payoff table optimizes each objective alone, which yields the ideal point (diagonal) and a nadir estimate (column maxima). The ranges vector turns the three incompatible units (k$/yr, ms, k$/yr) into dimensionless quantities.

Section 4: weight sweep. A grid with step $0.1$ over the simplex gives 66 weight vectors. Each one produces a normalized cost matrix norm_coef(w) and one MILP solve. Duplicate placements are merged, and a dominance filter removes any weakly dominated points, leaving the Pareto-optimal set. The optimal scalarized value for every weight is stored for the 3D surface plot.

Section 5: baselines. The balanced optimum uses equal weights. The greedy heuristic processes datasets from highest potential loss to lowest and assigns each to the cheapest feasible location under the balanced scalarization. The random baseline draws 3000 feasible placements by rejection sampling, which also gives the grey point cloud in the 3D plot.

Section 6: console report. The report prints the payoff table, the method comparison, the final placement, and the load per location.

Section 7: figure. All six panels share one figure with two rows and three columns:

  1. Risk–cost projection of the Pareto set, colored by mean latency.
  2. 3D objective space with the random cloud, Pareto points, greedy solution, and MILP optimum.
  3. Heat map of the optimal placement matrix.
  4. Normalized regret of each method on each objective.
  5. 3D surface of the optimal scalarized value over the weight simplex.
  6. Stacked storage volume per location for four representative solutions.

5. Console Output

=== Problem size ===
datasets: 12, locations: 5, binary variables: 60
feasible random placements sampled: 3000 (trials: 6322)

=== Payoff table (rows: optimised objective) ===
optimised for     risk [k$/yr]  latency [ms]  cost [k$/yr]
risk                    2382.0         50.73         151.3
latency                 3514.0         45.93         124.2
cost                    6875.0         81.81          83.9

=== Weighted-sum sweep: 66 MILPs in 0.61 s, 40 Pareto-optimal placements ===

=== Method comparison (balanced weights 1/3, 1/3, 1/3) ===
method                      risk   latency      cost     score
Random (mean)             4459.1     61.43     119.9    0.4762
Random (best of all)      3435.0     49.28     101.2    0.1949
Greedy heuristic          3434.0     46.58     101.9    0.1732
MILP optimum              3434.0     46.58     101.9    0.1732

=== Optimal placement (balanced weights) ===
dataset               TB  loss [M$]  location
Customer PII           8         50  On-prem Tokyo
Payment records       12         80  On-prem Tokyo
Employee HR            3         30  On-prem Tokyo
Source code            2         40  On-prem Osaka
Product catalog        5          2  Cloud Tokyo
Web analytics         40          5  Cloud Tokyo
Access logs           60          8  Cloud Tokyo
ML training set       80         20  Cloud Oregon
Backups              100         60  Cloud Singapore
Marketing assets      20          1  Cloud Tokyo
Sensor telemetry      50          3  Cloud Singapore
Partner contracts      1         25  On-prem Osaka

=== Load per location (balanced weights) ===
On-prem Tokyo           23 TB   exposed loss    160 M$
On-prem Osaka            3 TB   exposed loss     65 M$
Cloud Tokyo            125 TB   exposed loss     16 M$
Cloud Singapore        150 TB   exposed loss     63 M$
Cloud Oregon            80 TB   exposed loss     20 M$

6. Result Figure

7. Interpreting the Results

Pareto front (top left). The curve is a classic knee-shaped trade-off. Moving left lowers expected leak loss, but only by moving sensitive and large datasets into the expensive on-premises sites, so storage cost climbs. Moving right saves money by pushing data toward the cheap but riskier cloud regions. The color shows that latency does not move monotonically with either objective, because the best latency depends on which datasets sit near which users rather than on the total amount of data stored near anyone.

Objective space (top middle). The grey cloud shows what random feasible placements look like in the three-dimensional objective space. The Pareto-optimal points form a thin lower-left boundary of that cloud, which is exactly where a rational operator wants to be. The yellow star marks the balanced optimum, a compromise that is not extreme on any axis.

Placement matrix (top right). The structure of the balanced solution follows the economics. The highest-value, residency-bound datasets (customer PII, payment records, HR) go to the on-premises sites with the lowest breach probability. Large, low-sensitivity, high-traffic data such as product catalogs, analytics, and logs goes to Cloud Tokyo, which is close to the main users and cheap. The cheapest regions absorb the bulk data whose leak would hurt little, such as the ML training set, backups, and sensor telemetry. Backups are valuable but are accessed rarely, so latency barely matters for them and the blast-radius cap and cost decide their location.

Method comparison (bottom left). A random feasible placement is far from the ideal on all three axes. The greedy heuristic and the MILP optimum are both close to the ideal on latency and sit at moderate regret for risk and cost. On this small instance the greedy rule happens to reach the same placement as the exact solver, but it carries no optimality guarantee, and only the MILP can certify that no better balanced placement exists. The extreme solutions show the price of single-minded optimization: minimizing risk alone pushes cost to its worst value, and minimizing cost alone pushes risk and latency to their worst values.

Weight surface (bottom middle). The surface shows the best achievable normalized score for every weighting of the three objectives. It is concave because it is the pointwise minimum of linear functions of the weights, one for each feasible placement. The valleys at the corners correspond to the single-objective optima, where the score reaches zero. The ridge in the interior shows where no placement is simultaneously good on all objectives, which is the region where the choice of weights matters most.

Storage volume (bottom right). The stacked bars make the architectural consequence visible. The risk-minimizing placement fills both on-premises sites. The cost-minimizing placement puts nearly everything into the cheapest cloud region. The balanced placement spreads data across all locations, using on-premises capacity mainly for sensitive data and cloud capacity for the bulk of the volume.

8. Conclusion

Leak-aware placement is a small assignment problem with a large practical payoff. Writing breach probability as a coefficient of the objective, adding a blast-radius cap, and encoding residency as variable bounds turns a vague security discussion into a mixed-integer program that an off-the-shelf solver handles in moments. The Pareto sweep then gives decision makers a menu of efficient options rather than a single answer, so the final weights can reflect the organization’s actual appetite for risk, latency, and cost.

Optimizing the Privacy Budget ε in Differential Privacy

Getting the Most Utility Out of Every Bit of Privacy

Differential privacy (DP) gives a mathematically provable guarantee: whether or not any single individual is in a dataset, what an observer sees barely changes. The cost of that guarantee is noise, and the amount of noise is set by the privacy budget $\varepsilon$. A smaller $\varepsilon$ gives stronger privacy and noisier answers.

In practice an analyst rarely asks just one question. A data release usually holds a batch of statistics, and they all draw on one shared, limited budget. That raises the question this post answers:

How should we spend a privacy budget $\varepsilon$ — or how small can we make it — while keeping the released statistics as useful as possible?

We’ll set up a realistic example, derive the optimal answer in closed form, check it numerically, confirm it with Monte Carlo simulation, and visualize the whole privacy–utility trade-off, including in 3D.


The Problem Setting

A hospital holds records for $n = 5000$ patients and wants to publish five aggregate statistics:

# Query L1 sensitivity $\Delta_i$ Importance $\alpha_i$
1 Number of diabetic patients $1$ $1.0$
2 Number of rare-disease patients $1$ $2.0$
3 Sum of ages (clipped to $[0,100]$) $100$ $1.0$
4 Sum of incomes (clipped to $[0, 200{,}000]$) $200{,}000$ $1.5$
5 Sum of hospital visits (clipped to $[0,20]$) $20$ $0.5$

The rare-disease count is small (about 1% of patients), so the same noise hurts it much more in relative terms. The analyst also cares about it most.

The Laplace Mechanism

Each query $f_i$ is answered with the Laplace mechanism:

$$
\tilde{f}i(D) = f_i(D) + \mathrm{Lap}!\left(\frac{\Delta_i}{\varepsilon_i}\right),
\qquad
\Delta_i = \max
{D \sim D’} \lvert f_i(D) - f_i(D’) \rvert .
$$

Under sequential composition, releasing all five answers is $\varepsilon_{\text{total}}$-DP with

$$
\varepsilon_{\text{total}} = \sum_{i=1}^{K} \varepsilon_i .
$$

Measuring Utility

The noise variance of the Laplace mechanism is $\mathrm{Var}[\mathrm{Lap}(b)] = 2b^2$. To compare statistics with very different scales (a count of 58 against an income total of 240 million), we use the importance-weighted relative mean squared error:

$$
\mathrm{wMSE}(\boldsymbol{\varepsilon})
= \sum_{i=1}^{K} \alpha_i,\mathbb{E}!\left[\left(\frac{\tilde f_i - f_i}{f_i}\right)^{2}\right]
= \sum_{i=1}^{K} \frac{2\alpha_i \Delta_i^2}{f_i^2},\frac{1}{\varepsilon_i^2}
= \sum_{i=1}^{K} \frac{a_i}{\varepsilon_i^2},
\qquad a_i = \frac{2\alpha_i\Delta_i^2}{f_i^2}.
$$

Three Ways to Pose the Optimization

(P1) Primal — maximize utility for a fixed budget

$$
\min_{\boldsymbol{\varepsilon} > 0} \ \sum_{i=1}^{K} \frac{a_i}{\varepsilon_i^2}
\quad \text{s.t.} \quad \sum_{i=1}^{K} \varepsilon_i = E .
$$

(P2) Dual — minimize the budget for a utility target

$$
\min_{\boldsymbol{\varepsilon} > 0} \ \sum_{i=1}^{K} \varepsilon_i
\quad \text{s.t.} \quad \sum_{i=1}^{K} \frac{a_i}{\varepsilon_i^2} \le U .
$$

(P3) Penalized — trade privacy and utility with a price $\lambda$

$$
\min_{E > 0} \ J(E) = \mathrm{wMSE}^*(E) + \lambda E .
$$

Closed-Form Solution

For (P1), the Lagrangian $\mathcal{L} = \sum_i a_i\varepsilon_i^{-2} + \mu\left(\sum_i \varepsilon_i - E\right)$ gives

$$
\frac{\partial \mathcal{L}}{\partial \varepsilon_i} = -\frac{2a_i}{\varepsilon_i^3} + \mu = 0
;\Longrightarrow;
\varepsilon_i \propto a_i^{1/3}.
$$

Normalizing to the budget:

The objective is strictly convex on the positive orthant, so this stationary point is the unique global optimum. Splitting the budget evenly, $\varepsilon_i = E/K$, gives

$$
\mathrm{wMSE}^{\text{unif}}(E) = \frac{K^2 \sum_j a_j}{E^2}.
$$

Solving (P2) by inverting the same relation gives

$$
E_{\min}^{*} = \sqrt{\frac{S^3}{U}},
\qquad
E_{\min}^{\text{unif}} = K\sqrt{\frac{\sum_j a_j}{U}},
$$

so the relative budget saving $1 - \dfrac{S^{3/2}}{K\sqrt{\sum_j a_j}}$ does not depend on the target $U$.

For (P3), setting $J’(E) = -2S^3/E^3 + \lambda = 0$ gives

$$
E^{*}(\lambda) = \left(\frac{2S^3}{\lambda}\right)^{1/3}.
$$

We’ll also use a tail-probability version of utility. Since $P(\lvert \mathrm{Lap}(b)\rvert > t) = e^{-t/b}$, requiring each query to be within a relative tolerance $\tau$ with probability at least $1-\beta$ gives

$$
P!\left(\lvert \tilde f_i - f_i \rvert > \tau f_i\right) \le \beta
;\Longleftrightarrow;
\varepsilon_i \ge \frac{\Delta_i \ln(1/\beta)}{\tau f_i}.
$$


Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import time
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # noqa: F401
from scipy.optimize import minimize

rng = np.random.default_rng(42)

# ------------------------------------------------------------
# 1. Synthetic patient database
# ------------------------------------------------------------
n = 5000
age = np.clip(rng.normal(48, 18, n), 0, 100)
income = np.clip(rng.lognormal(10.6, 0.6, n), 0, 200_000)
visits = np.clip(rng.poisson(3.0, n), 0, 20)
diabetic = rng.random(n) < (0.05 + 0.15 * (age > 60))
rare = rng.random(n) < 0.012

names = ["Diabetic count", "Rare-disease count", "Sum of age",
"Sum of income", "Sum of visits"]
true_vals = np.array([diabetic.sum(), rare.sum(), age.sum(),
income.sum(), visits.sum()], dtype=float)
sens = np.array([1.0, 1.0, 100.0, 200_000.0, 20.0]) # L1 sensitivity (add/remove)
importance = np.array([1.0, 2.0, 1.0, 1.5, 0.5]) # analyst priorities
w = importance / true_vals**2 # weighted relative MSE
a = 2.0 * w * sens**2 # cost coefficients
K = len(names)

# ------------------------------------------------------------
# 2. Closed-form optimal allocation
# ------------------------------------------------------------
S = np.sum(a ** (1 / 3))

def optimal_alloc(E):
return E * a ** (1 / 3) / S

def uniform_alloc(E):
return np.full(K, E / K)

def wmse(eps):
return np.sum(a / eps**2, axis=-1)

def wmse_opt(E):
return S**3 / np.asarray(E, dtype=float)**2

def wmse_unif(E):
return K**2 * a.sum() / np.asarray(E, dtype=float)**2

# ------------------------------------------------------------
# 3. Numerical cross-check with SLSQP (on the simplex of shares)
# ------------------------------------------------------------
def slsqp_alloc(E):
obj = lambda x: np.sum(a / x**2) / S**3
jac = lambda x: -2.0 * a / x**3 / S**3
cons = {"type": "eq", "fun": lambda x: np.sum(x) - 1.0,
"jac": lambda x: np.ones(K)}
res = minimize(obj, np.full(K, 1.0 / K), jac=jac, method="SLSQP",
bounds=[(1e-6, 1.0)] * K, constraints=[cons],
options={"ftol": 1e-14, "maxiter": 500})
return E * res.x

E0 = 1.0
eps_opt = optimal_alloc(E0)
eps_uni = uniform_alloc(E0)
t0 = time.perf_counter()
eps_slsqp = slsqp_alloc(E0)
t_slsqp = time.perf_counter() - t0
t0 = time.perf_counter()
for _ in range(1000):
optimal_alloc(E0)
t_closed = (time.perf_counter() - t0) / 1000

print("=" * 72)
print(f"Total privacy budget epsilon = {E0}")
print("=" * 72)
print(f"{'Query':<20}{'True value':>14}{'Delta':>10}{'eps_unif':>10}{'eps_opt':>10}{'eps_SLSQP':>11}")
for i in range(K):
print(f"{names[i]:<20}{true_vals[i]:>14.1f}{sens[i]:>10.0f}"
f"{eps_uni[i]:>10.4f}{eps_opt[i]:>10.4f}{eps_slsqp[i]:>11.4f}")
print("-" * 72)
print(f"Weighted MSE (uniform) : {wmse(eps_uni):.6e}")
print(f"Weighted MSE (optimal) : {wmse(eps_opt):.6e}")
print(f"Weighted MSE (SLSQP) : {wmse(eps_slsqp):.6e}")
print(f"Error reduction : {100 * (1 - wmse(eps_opt) / wmse(eps_uni)):.2f} %")
print(f"Max |closed - SLSQP| : {np.max(np.abs(eps_opt - eps_slsqp)):.2e}")
print(f"Time closed form : {t_closed * 1e6:.2f} us")
print(f"Time SLSQP : {t_slsqp * 1e3:.2f} ms")

# ------------------------------------------------------------
# 4. Vectorized Monte Carlo verification
# ------------------------------------------------------------
T = 20000
t0 = time.perf_counter()
noise_u = rng.laplace(0.0, sens / eps_uni, size=(T, K))
noise_o = rng.laplace(0.0, sens / eps_opt, size=(T, K))
rel_u = np.abs(noise_u) / true_vals
rel_o = np.abs(noise_o) / true_vals
mc_u = np.mean(np.sum(importance * (noise_u / true_vals) ** 2, axis=1))
mc_o = np.mean(np.sum(importance * (noise_o / true_vals) ** 2, axis=1))
t_mc = time.perf_counter() - t0
print("=" * 72)
print(f"Monte Carlo ({T} releases, {t_mc * 1e3:.1f} ms)")
print(f"Empirical weighted MSE (uniform) : {mc_u:.6e}")
print(f"Empirical weighted MSE (optimal) : {mc_o:.6e}")
print(f"{'Query':<20}{'median rel.err unif':>22}{'median rel.err opt':>22}")
for i in range(K):
print(f"{names[i]:<20}{np.median(rel_u[:, i]) * 100:>21.3f}%{np.median(rel_o[:, i]) * 100:>21.3f}%")

# ------------------------------------------------------------
# 5. Dual problem: minimum epsilon for a utility target
# ------------------------------------------------------------
targets = np.linspace(0.01, 0.20, 100) # average relative RMSE target
U = importance.sum() * targets**2
E_min_opt = np.sqrt(S**3 / U)
E_min_uni = K * np.sqrt(a.sum() / U)

print("=" * 72)
print("Dual problem: minimum total epsilon to reach a weighted-RMSE target")
for r in [0.02, 0.05, 0.10]:
Ur = importance.sum() * r**2
eo, eu = np.sqrt(S**3 / Ur), K * np.sqrt(a.sum() / Ur)
print(f"target {r * 100:4.1f}% : eps_opt = {eo:7.4f} eps_unif = {eu:7.4f}"
f" saving = {100 * (1 - eo / eu):5.2f} %")

beta, tol = 0.05, 0.05
eps_tail = sens * np.log(1 / beta) / (tol * true_vals)
print("-" * 72)
print(f"Per-query guarantee P(|error| > {tol * 100:.0f}% of truth) <= {beta}")
for i in range(K):
print(f"{names[i]:<20} eps_i >= {eps_tail[i]:.5f}")
print(f"Minimum total epsilon: {eps_tail.sum():.5f}")

# ------------------------------------------------------------
# 6. Penalized formulation: min wMSE(E) + lambda * E
# ------------------------------------------------------------
lams = np.logspace(-6, -1, 80)
E_star = (2 * S**3 / lams) ** (1 / 3)
print("=" * 72)
for lam in [1e-5, 1e-4, 1e-3, 1e-2]:
print(f"lambda = {lam:.0e} -> optimal total epsilon E* = {(2 * S**3 / lam) ** (1 / 3):.4f}")
print("=" * 72)

# ------------------------------------------------------------
# 7. Visualization (2 x 3)
# ------------------------------------------------------------
fig = plt.figure(figsize=(21, 12))

# (1) Allocation bars
ax1 = fig.add_subplot(2, 3, 1)
x = np.arange(K)
ax1.bar(x - 0.27, eps_uni, 0.27, label="Uniform", color="#9aa5b1")
ax1.bar(x, eps_opt, 0.27, label="Optimal (closed form)", color="#2b6cb0")
ax1.bar(x + 0.27, eps_slsqp, 0.27, label="SLSQP", color="#ed8936")
ax1.set_xticks(x)
ax1.set_xticklabels(names, rotation=25, ha="right")
ax1.set_ylabel(r"$\varepsilon_i$")
ax1.set_title(r"Budget allocation at $\varepsilon_{total}=1$")
ax1.legend()
ax1.grid(axis="y", alpha=0.3)

# (2) Privacy-utility frontier
ax2 = fig.add_subplot(2, 3, 2)
Es = np.logspace(-1.5, 1, 120)
ax2.loglog(Es, wmse_unif(Es), "--", color="#9aa5b1", lw=2, label="Uniform")
ax2.loglog(Es, wmse_opt(Es), color="#2b6cb0", lw=2, label="Optimal")
Ech = np.logspace(-1.5, 1, 8)
ax2.loglog(Ech, [wmse(slsqp_alloc(e)) for e in Ech], "o", color="#ed8936", label="SLSQP check")
ax2.set_xlabel(r"Total budget $\varepsilon_{total}$")
ax2.set_ylabel("Weighted relative MSE")
ax2.set_title("Privacy-utility frontier")
ax2.legend()
ax2.grid(True, which="both", alpha=0.3)

# (3) 3D surface of wMSE over shares of two queries
ax3 = fig.add_subplot(2, 3, 3, projection="3d")
i1, i2 = 1, 3
rest = [j for j in range(K) if j not in (i1, i2)]
S_rest = np.sum(a[rest] ** (1 / 3))
g = np.linspace(0.02, 0.9, 90)
X, Y = np.meshgrid(g, g)
Rm = 1.0 - X - Y
valid = Rm > 0.02
Z = np.full_like(X, np.nan)
Z[valid] = (a[i1] / (E0 * X[valid])**2 + a[i2] / (E0 * Y[valid])**2
+ S_rest**3 / (E0 * Rm[valid])**2)
Zl = np.log10(Z)
ax3.plot_surface(X, Y, Zl, cmap="viridis", alpha=0.85, edgecolor="none")
xo, yo = eps_opt[i1] / E0, eps_opt[i2] / E0
ax3.scatter([xo], [yo], [np.log10(wmse(eps_opt))], color="red", s=80, depthshade=False)
ax3.set_xlabel(f"Share: {names[i1]}")
ax3.set_ylabel(f"Share: {names[i2]}")
ax3.set_zlabel(r"$\log_{10}$ wMSE")
ax3.set_title("Objective landscape (red = optimum)")
ax3.view_init(elev=28, azim=-130)

# (4) Monte Carlo relative errors
ax4 = fig.add_subplot(2, 3, 4)
pos = np.arange(K)
bu = ax4.boxplot([rel_u[:, i] * 100 for i in range(K)], positions=pos - 0.18,
widths=0.3, patch_artist=True, showfliers=False)
bo = ax4.boxplot([rel_o[:, i] * 100 for i in range(K)], positions=pos + 0.18,
widths=0.3, patch_artist=True, showfliers=False)
for b in bu["boxes"]:
b.set_facecolor("#cbd2d9")
for b in bo["boxes"]:
b.set_facecolor("#90cdf4")
ax4.set_yscale("log")
ax4.set_xticks(pos)
ax4.set_xticklabels(names, rotation=25, ha="right")
ax4.set_ylabel("Absolute relative error [%]")
ax4.set_title("Monte Carlo errors (grey: uniform, blue: optimal)")
ax4.grid(axis="y", which="both", alpha=0.3)

# (5) Dual problem
ax5 = fig.add_subplot(2, 3, 5)
ax5.plot(targets * 100, E_min_uni, "--", color="#9aa5b1", lw=2, label="Uniform")
ax5.plot(targets * 100, E_min_opt, color="#2b6cb0", lw=2, label="Optimal")
ax5.fill_between(targets * 100, E_min_opt, E_min_uni, color="#90cdf4", alpha=0.4,
label="Budget saved")
ax5.set_yscale("log")
ax5.set_xlabel("Target average relative RMSE [%]")
ax5.set_ylabel(r"Minimum $\varepsilon_{total}$")
ax5.set_title("Minimum privacy cost for a utility target")
ax5.legend()
ax5.grid(True, which="both", alpha=0.3)

# (6) 3D penalized objective
ax6 = fig.add_subplot(2, 3, 6, projection="3d")
le = np.linspace(-1.5, 1.5, 70)
ll = np.linspace(-6, -1, 70)
LE, LL = np.meshgrid(le, ll)
J = S**3 / (10**LE)**2 + (10**LL) * (10**LE)
ax6.plot_surface(LE, LL, np.log10(J), cmap="plasma", alpha=0.8, edgecolor="none")
mask = (np.log10(E_star) >= -1.5) & (np.log10(E_star) <= 1.5)
Jstar = S**3 / E_star**2 + lams * E_star
ax6.plot(np.log10(E_star[mask]), np.log10(lams[mask]), np.log10(Jstar[mask]),
color="cyan", lw=3, label=r"$\varepsilon^*(\lambda)$")
ax6.set_xlabel(r"$\log_{10}\varepsilon_{total}$")
ax6.set_ylabel(r"$\log_{10}\lambda$")
ax6.set_zlabel(r"$\log_{10} J$")
ax6.set_title(r"Penalized objective $J=\mathrm{wMSE}+\lambda\varepsilon$")
ax6.legend()
ax6.view_init(elev=25, azim=-60)

plt.tight_layout()
plt.show()

Code Walkthrough

1. Synthetic patient database

We draw 5,000 synthetic patients from a seeded generator (default_rng(42)), so every run gives the same results. Each attribute is clipped to a fixed range. Clipping is what makes the sensitivities finite and known: adding or removing one patient can change the age sum by at most 100, the income sum by at most 200,000, and the visit sum by at most 20. A count changes by at most 1.

Diabetes is more likely above age 60. The rare disease affects about 1.2% of patients, so its count is only 58. That count is the hard case of the problem.

The vector a holds the coefficients $a_i = 2\alpha_i\Delta_i^2/f_i^2$ from the derivation, so the whole problem reduces to $\sum_i a_i/\varepsilon_i^2$.

2. Closed-form optimal allocation

optimal_alloc(E) implements $\varepsilon_i^* = E,a_i^{1/3}/S$ directly. It’s a single vectorized NumPy expression that takes about 2 microseconds. wmse_opt and wmse_unif are the analytic error formulas $S^3/E^2$ and $K^2\sum a_j/E^2$. With them we can draw whole frontier curves without running any optimizer.

3. Numerical cross-check with SLSQP

To confirm the derivation, we solve the same problem with SciPy’s SLSQP. Two choices keep the solver fast and stable:

  • Optimizing over budget shares $x_i = \varepsilon_i/E$ on the simplex $\sum_i x_i = 1$. This makes the problem independent of scale.
  • Supplying the analytic gradient $-2a_i/x_i^3$ and dividing the objective by $S^3$, so its value is of order 1 at the optimum.

The solver agrees with the closed form to about $10^{-9}$. It takes milliseconds, against microseconds for the formula. This is where the closed form pays off: if you need allocations for thousands of budgets, as in a frontier plot or a dashboard, the formula is effectively free.

4. Vectorized Monte Carlo verification

Theory says the optimal allocation should give a smaller expected error. To check, we simulate 20,000 independent releases under each allocation. All the Laplace noise is drawn in one rng.laplace(..., size=(T, K)) call. NumPy broadcasts the per-query scale $\Delta_i/\varepsilon_i$ across the columns, so there is no Python loop, and 40,000 five-query releases take a few milliseconds. The empirical weighted MSE should match $S^3/E^2$ and $K^2\sum a_j/E^2$.

5. Dual problem: minimum ε for a utility target

Here we flip the question. We set a target average relative RMSE $r$, so $U = \left(\sum_i \alpha_i\right) r^2$, and compute the smallest budget that reaches it: $E^*_{\min} = \sqrt{S^3/U}$. We compare this with the budget an even split would need.

The second block applies the stricter tail-probability guarantee. Each query must be within 5% of its true value with 95% probability. This sets a per-query floor $\varepsilon_i \ge \Delta_i\ln(1/\beta)/(\tau f_i)$, and the floors add up to the minimum total budget.

6. Penalized formulation

If an organization can put a “price” $\lambda$ on each unit of privacy loss, the best total budget is $E^*(\lambda) = (2S^3/\lambda)^{1/3}$. The code prints this for several values of $\lambda$ and also sweeps $\lambda$ for the 3D plot.

7. Visualization

All six panels share one 2 × 3 figure. Two of them are 3D surfaces: the objective landscape over the budget simplex, and the penalized objective over $(\varepsilon, \lambda)$.


Execution Results

========================================================================
Total privacy budget epsilon = 1.0
========================================================================
Query                   True value     Delta  eps_unif   eps_opt  eps_SLSQP
Diabetic count               436.0         1    0.2000    0.1372     0.1372
Rare-disease count            58.0         1    0.2000    0.6633     0.6633
Sum of age                238273.1       100    0.2000    0.0442     0.0442
Sum of income          240183538.8    200000    0.2000    0.0799     0.0799
Sum of visits              15164.0        20    0.2000    0.0753     0.0753
------------------------------------------------------------------------
Weighted MSE (uniform) : 3.009384e-02
Weighted MSE (optimal) : 4.073663e-03
Weighted MSE (SLSQP)   : 4.073663e-03
Error reduction        : 86.46 %
Max |closed - SLSQP|   : 5.71e-09
Time closed form       : 6.42 us
Time SLSQP             : 11.07 ms
========================================================================
Monte Carlo (20000 releases, 20.6 ms)
Empirical weighted MSE (uniform) : 2.986664e-02
Empirical weighted MSE (optimal) : 4.085240e-03
Query                  median rel.err unif    median rel.err opt
Diabetic count                      0.789%                1.185%
Rare-disease count                  6.005%                1.811%
Sum of age                          0.143%                0.671%
Sum of income                       0.289%                0.716%
Sum of visits                       0.457%                1.210%
========================================================================
Dual problem: minimum total epsilon to reach a weighted-RMSE target
target  2.0% : eps_opt =  1.3028   eps_unif =  3.5411   saving = 63.21 %
target  5.0% : eps_opt =  0.5211   eps_unif =  1.4164   saving = 63.21 %
target 10.0% : eps_opt =  0.2606   eps_unif =  0.7082   saving = 63.21 %
------------------------------------------------------------------------
Per-query guarantee P(|error| > 5% of truth) <= 0.05
Diabetic count       eps_i >= 0.13742
Rare-disease count   eps_i >= 1.03301
Sum of age           eps_i >= 0.02515
Sum of income        eps_i >= 0.04989
Sum of visits        eps_i >= 0.07902
Minimum total epsilon: 1.32449
========================================================================
lambda = 1e-05 -> optimal total epsilon E* = 9.3398
lambda = 1e-04 -> optimal total epsilon E* = 4.3352
lambda = 1e-03 -> optimal total epsilon E* = 2.0122
lambda = 1e-02 -> optimal total epsilon E* = 0.9340
========================================================================

Reading the Results

Top-left: Budget allocation at $\varepsilon_{\text{total}} = 1$

The even split gives every query $0.2$. The optimal split is very uneven:

  • The rare-disease count gets about $0.66$, two-thirds of the whole budget. Its true value is tiny (58), so Laplace noise of scale $1/\varepsilon$ is large relative to it, and the analyst gave it twice the importance.
  • The age sum gets only about $0.044$. Its sensitivity of 100 sounds large, but next to a total of about 238,000 it is negligible, so it needs very little budget.
  • The closed-form bars (blue) and the SLSQP bars (orange) match exactly, which confirms the $a_i^{1/3}$ rule.

The rule $\varepsilon_i \propto \left(\alpha_i \Delta_i^2 / f_i^2\right)^{1/3}$ amounts to this: give budget to queries whose relative sensitivity $\Delta_i/f_i$ is large, and temper it with the cube root, so no single query takes everything.

Top-center: Privacy–utility frontier

Both curves are straight lines with slope $-2$ on log–log axes, since error scales as $1/\varepsilon^2$. The optimal line sits a constant factor below the even split at every budget. Here the weighted MSE drops from about $3.0\times10^{-2}$ to $4.1\times10^{-3}$, an 86% reduction, at no extra privacy cost. The orange SLSQP points land on the analytic curve at all eight budgets checked.

Top-right (3D): Objective landscape

We fix the total budget and vary the shares going to the rare-disease count and to the income sum. The other three queries share what’s left, split optimally among themselves. The surface is a convex bowl. It shoots up toward the edges, where some query’s budget goes to zero and its error blows up. The red dot at the bottom of the bowl is the closed-form optimum. Convexity is why the Lagrangian solution is global and why any gradient-based solver converges to it.

Bottom-left: Monte Carlo relative errors

This panel shows how the gains are distributed across queries. With an even split, the rare-disease count has a median relative error of about 6% and a long upper tail. The optimal allocation cuts that to about 1.8%. The other queries get slightly worse, from fractions of a percent to roughly 1%. That is the intended trade: budget moves from queries that were over-served to the one that was failing. The empirical weighted MSE from the simulation matches the theoretical values closely.

Bottom-center: Minimum privacy cost for a utility target

This panel answers the dual question. For any accuracy target, the optimal allocation reaches it with a much smaller $\varepsilon$. The shaded band is the budget saved. As the closed-form analysis predicts, the saving is a constant 63.2% regardless of the target. For example, a 5% average relative RMSE needs $\varepsilon \approx 0.52$ with optimal allocation, against $\approx 1.42$ with an even split. In DP terms, that is a much stronger privacy guarantee for exactly the same accuracy.

The console also reports the stricter per-query tail guarantee: each answer within 5% of the truth with 95% probability. That needs $\varepsilon_{\text{total}} \approx 1.32$, and over 1.03 of it goes to the rare-disease count alone. Small counts are the bottleneck of almost every DP release, and this per-query floor quantifies that exactly.

Bottom-right (3D): Penalized objective

The surface shows $J = \mathrm{wMSE}^*(\varepsilon) + \lambda\varepsilon$ over $\log\varepsilon$ and $\log\lambda$. For each $\lambda$, the cross-section is a valley: too little budget and the error term dominates, too much and the privacy penalty dominates. The cyan curve runs along the valley floor, following $\varepsilon^*(\lambda) = (2S^3/\lambda)^{1/3}$. As privacy gets ten times more expensive, the best budget shrinks by a factor of $10^{1/3} \approx 2.15$ (from 9.34 to 4.34 to 2.01 to 0.93 in the console output). This gives a principled way to choose $\varepsilon$ itself, not just how to split it.


Takeaways

  • With Laplace noise and a squared-error utility, the best way to split a fixed budget is $\varepsilon_i^* \propto \left(\alpha_i\Delta_i^2/f_i^2\right)^{1/3}$, and it comes in closed form.
  • Splitting the budget evenly can be very wasteful. In this example the optimal split cut the error by 86% at the same $\varepsilon$, or reached the same accuracy with 63% less privacy budget.
  • The same machinery answers three practical questions: how to split a fixed budget (primal), how small the budget can be for a required accuracy (dual), and what total budget to choose given a price on privacy (penalized).
  • Small counts dominate the privacy cost. Optimization automatically shifts budget toward them, and the per-query tail bound shows exactly how much they need.
  • One caution: we plugged the true values $f_i$ into the weights. In a real deployment those weights should come from public information, prior estimates, or a small, separately accounted slice of the budget, so the allocation itself leaks nothing.

Finding the Best Generalization Under a Re-identification Risk Budget

Privacy vs. Utility in Data Anonymization:

Anyone who releases microdata (patient records, customer logs, survey responses) runs into the same tension. The more you mask, the safer the data gets, and the less useful it becomes. Coarsen ages into decades and truncate ZIP codes to one digit, and nobody can single out an individual, but your regression model loses most of what it could explain. Leave everything raw and the model performs well, but almost every record becomes uniquely identifiable.

In this article we turn that tension into an explicit constrained optimization problem. Our goal is to keep the re-identification risk below a fixed threshold while making the anonymized data as useful as possible for analysis. We then solve it in Python.


The Problem Setting

A health insurer wants to share 30,000 member records with an external analytics team. The team will build a model that predicts annual medical cost. Each record contains:

Attribute Role
Age (18–89) Quasi-identifier
Gender Quasi-identifier
5-digit ZIP code Quasi-identifier
Annual income Quasi-identifier
Annual medical cost Sensitive / target variable

None of these attributes names a person directly. Combined, though, they act as a fingerprint. “A 47-year-old woman in ZIP 31402 earning $62,300” is almost certainly one specific person.

The insurer can apply generalization to each quasi-identifier:

  • Age: bin width $w_a \in {1, 2, 5, 10, 20, 40}$ years
  • ZIP code: keep the first $d_z \in {5, 4, 3, 2, 1, 0}$ digits
  • Income: bin width $w_i \in {1\text{k}, 5\text{k}, 10\text{k}, 25\text{k}, 50\text{k}, 100\text{k}}$

That gives $6 \times 6 \times 6 = 216$ candidate anonymization schemes, which together form a generalization lattice.


Formalizing the Trade-off

Equivalence classes and k-anonymity

After generalization, records that share the same quasi-identifier values form an equivalence class. Let $|E(r)|$ be the size of the class that contains record $r$. A dataset is $k$-anonymous when

$$
\min_{r} |E(r)| \ge k .
$$

Strict $k$-anonymity is often too harsh, because a single outlier can force the whole dataset into very coarse bins. A common relaxation is to cap the share of records at risk:

$$
R_{\text{at-risk}}(\theta) = \frac{1}{N}\sum_{r=1}^{N} \mathbf{1}\bigl[,|E_\theta(r)| < k,\bigr],
$$

where $\theta = (w_a, d_z, w_i)$ is the generalization scheme. The few records still at risk can be suppressed or handled individually.

We also report the average prosecutor risk. This is the expected probability that an attacker who knows a target’s quasi-identifiers picks the right record:

$$
R_{\text{avg}}(\theta) = \frac{1}{N}\sum_{r=1}^{N} \frac{1}{|E_\theta(r)|}.
$$

Utility

Utility is measured by what the analysts actually care about: the out-of-sample $R^2$ of a cost-prediction model trained on the generalized data.

$$
U(\theta) = R^2_{\text{test}}(\theta) = 1 - \frac{\sum_{j \in \text{test}} (y_j - \hat y_j)^2}{\sum_{j \in \text{test}} (y_j - \bar y)^2}.
$$

The optimization problem

$$
\theta^* = \arg\max_{\theta \in \Theta} ; U(\theta)
\quad \text{s.t.} \quad R_{\text{at-risk}}(\theta) \le \varepsilon,
$$

with $k = 5$ and $\varepsilon = 0.05$. In words: at most 5% of the records may sit in an equivalence class smaller than 5.


The Data-Generating Process

We generate synthetic data whose true cost structure is known, so the effect of each generalization can be interpreted directly:

$$
y = 1500 + 4,(a-18)^{1.6} + 350,g + \alpha_{d_1} + \beta_{d_1 d_2} + \gamma_{d_1 d_2 d_3} - 0.012,x + \epsilon ,
$$

where $a$ is age, $g$ is gender, $x$ is income, $\epsilon \sim \mathcal{N}(0, 700^2)$, and the regional effects form a hierarchy:

$$
\alpha_{d_1} \sim \mathcal{N}(0, 900^2), \quad
\beta_{d_1 d_2} \sim \mathcal{N}(0, 600^2), \quad
\gamma_{d_1 d_2 d_3} \sim \mathcal{N}(0, 400^2).
$$

So the first three ZIP digits carry real signal, and digits 4–5 are pure noise from the model’s point of view but highly identifying. This mirrors reality, where coarse geography explains a lot and fine geography mostly fingerprints people.


Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D # noqa: F401
import time

rng = np.random.default_rng(42)

# ------------------------------------------------------------
# 1. Synthetic microdata
# ------------------------------------------------------------
N = 30000
age = rng.integers(18, 90, N)
gender = rng.integers(0, 2, N)
d1 = rng.integers(0, 10, N)
d2 = rng.integers(0, 10, N)
d345 = rng.integers(0, 1000, N)
zipcode = d1 * 10000 + d2 * 1000 + d345
income = np.clip(rng.lognormal(mean=np.log(45000) + 0.004 * (age - 18), sigma=0.45, size=N), 8000, 400000)

state_eff = rng.normal(0, 900, 10)
region_eff = rng.normal(0, 600, (10, 10))
area_eff = rng.normal(0, 400, (10, 10, 10))
d3 = d345 // 100
cost = (1500 + 4.0 * (age - 18) ** 1.6 + 350 * gender
+ state_eff[d1] + region_eff[d1, d2] + area_eff[d1, d2, d3]
- 0.012 * income + rng.normal(0, 700, N))

df = pd.DataFrame({"age": age, "gender": gender, "zip": zipcode,
"income": income, "cost": cost})

is_train = rng.random(N) < 0.7
y = df["cost"].to_numpy()
N_FOLD = 5
fold = rng.integers(0, N_FOLD, N)

# ------------------------------------------------------------
# 2. Generalization operators
# ------------------------------------------------------------
def generalize(age_w, zip_d, inc_w):
a_bin = (df["age"].to_numpy() // age_w).astype(np.int64)
a_mid = a_bin * age_w + age_w / 2.0
z_pre = (df["zip"].to_numpy() // 10 ** (5 - zip_d)).astype(np.int64)
i_bin = (df["income"].to_numpy() // inc_w).astype(np.int64)
i_mid = i_bin * inc_w + inc_w / 2.0
return a_bin, a_mid, z_pre, i_bin, i_mid

# ------------------------------------------------------------
# 3. Re-identification risk (fast: integer key + np.unique)
# ------------------------------------------------------------
K = 5
def risk_metrics(a_bin, z_pre, i_bin):
key = ((a_bin * 100001 + z_pre) * 2 + df["gender"].to_numpy()) * 1000 + i_bin
_, inv, cnt = np.unique(key, return_inverse=True, return_counts=True)
size = cnt[inv]
at_risk = np.mean(size < K)
avg_risk = np.mean(1.0 / size)
return at_risk, avg_risk, size.min(), size

# ------------------------------------------------------------
# 4. Utility: OLS on generalized data with target-encoded ZIP prefix
# ------------------------------------------------------------
def utility(a_mid, z_pre, zip_d, i_mid):
tr = is_train
gmean = y[tr].mean()
m = 20.0
cols = [np.ones(N), (a_mid - 50) / 10, ((a_mid - 50) / 10) ** 2, ((a_mid - 50) / 10) ** 3,
df["gender"].to_numpy(), i_mid / 1e4]
for L in range(1, zip_d + 1):
pre = z_pre // 10 ** (zip_d - L)
enc = np.empty(N)
# out-of-fold encoding for training rows (prevents target leakage)
for f in range(N_FOLD):
fit = tr & (fold != f)
app = tr & (fold == f)
s = pd.Series(y[fit]).groupby(pre[fit]).agg(["sum", "count"])
mp = (s["sum"] + m * gmean) / (s["count"] + m)
enc[app] = pd.Series(pre[app]).map(mp).fillna(gmean).to_numpy()
# full-train encoding for test rows
s = pd.Series(y[tr]).groupby(pre[tr]).agg(["sum", "count"])
mp = (s["sum"] + m * gmean) / (s["count"] + m)
enc[~tr] = pd.Series(pre[~tr]).map(mp).fillna(gmean).to_numpy()
cols.append(enc)
X = np.column_stack(cols)
beta, *_ = np.linalg.lstsq(X[tr], y[tr], rcond=None)
pred = X[~tr] @ beta
yt = y[~tr]
return 1 - np.sum((yt - pred) ** 2) / np.sum((yt - yt.mean()) ** 2)

# ------------------------------------------------------------
# 5. Grid search over the anonymization lattice
# ------------------------------------------------------------
AGE_W = [1, 2, 5, 10, 20, 40]
ZIP_D = [5, 4, 3, 2, 1, 0]
INC_W = [1000, 5000, 10000, 25000, 50000, 100000]
RISK_MAX = 0.05

t0 = time.time()
rows = []
for aw in AGE_W:
for zd in ZIP_D:
for iw in INC_W:
a_bin, a_mid, z_pre, i_bin, i_mid = generalize(aw, zd, iw)
at_risk, avg_risk, kmin, _ = risk_metrics(a_bin, z_pre, i_bin)
r2 = utility(a_mid, z_pre, zd, i_mid)
rows.append((aw, zd, iw, at_risk, avg_risk, kmin, r2))
res = pd.DataFrame(rows, columns=["age_w", "zip_d", "inc_w", "at_risk", "avg_risk", "k_min", "r2"])
elapsed = time.time() - t0

r2_orig = res.query("age_w==1 and zip_d==5 and inc_w==1000")["r2"].iloc[0]
risk_orig = res.query("age_w==1 and zip_d==5 and inc_w==1000")["at_risk"].iloc[0]
feas = res[res["at_risk"] <= RISK_MAX]
best = feas.sort_values(["r2", "k_min"], ascending=[False, False]).iloc[0]

# Pareto front (min risk, max r2)
srt = res.sort_values(["at_risk", "r2"], ascending=[True, False])
pareto, best_r2 = [], -np.inf
for _, r in srt.iterrows():
if r["r2"] > best_r2:
pareto.append(r)
best_r2 = r["r2"]
pareto = pd.DataFrame(pareto)

print(f"Configurations evaluated : {len(res)} ({elapsed:.2f} s)")
print(f"Raw data : R2 = {r2_orig:.4f}, records at risk (k<{K}) = {risk_orig:.3%}")
print(f"Feasible configurations (risk <= {RISK_MAX:.0%}) : {len(feas)}")
print("Optimal configuration:")
print(f" age bin width = {int(best.age_w)} years, ZIP digits kept = {int(best.zip_d)}, "
f"income bin width = {int(best.inc_w):,}")
print(f" R2 = {best.r2:.4f} ({best.r2 / r2_orig:.1%} of raw utility)")
print(f" records at risk = {best.at_risk:.3%}, average risk = {best.avg_risk:.4f}, k_min = {int(best.k_min)}")
print("\nTop 5 feasible configurations:")
print(feas.sort_values("r2", ascending=False).head(5).to_string(index=False))

# ------------------------------------------------------------
# 6. Visualization (2 x 3)
# ------------------------------------------------------------
fig = plt.figure(figsize=(21, 12))
iw_best = best.inc_w
sub = res[res["inc_w"] == iw_best]
A, Z = np.meshgrid(np.arange(len(AGE_W)), np.arange(len(ZIP_D)), indexing="ij")
R2g = np.zeros(A.shape); RKg = np.zeros(A.shape)
for i, aw in enumerate(AGE_W):
for j, zd in enumerate(ZIP_D):
r = sub[(sub.age_w == aw) & (sub.zip_d == zd)].iloc[0]
R2g[i, j] = r.r2; RKg[i, j] = r.at_risk

ax1 = fig.add_subplot(2, 3, 1, projection="3d")
ax1.plot_surface(A, Z, R2g, cmap=cm.viridis, edgecolor="k", linewidth=0.3, alpha=0.9)
ax1.set_xticks(range(len(AGE_W))); ax1.set_xticklabels(AGE_W)
ax1.set_yticks(range(len(ZIP_D))); ax1.set_yticklabels(ZIP_D)
ax1.set_xlabel("Age bin width"); ax1.set_ylabel("ZIP digits kept"); ax1.set_zlabel("R²")
ax1.set_title(f"Utility surface (income bin = {int(iw_best):,})")
ax1.view_init(28, -130)

ax2 = fig.add_subplot(2, 3, 2, projection="3d")
ax2.plot_surface(A, Z, RKg, cmap=cm.inferno, edgecolor="k", linewidth=0.3, alpha=0.9)
ax2.plot_surface(A, Z, np.full(A.shape, RISK_MAX), color="cyan", alpha=0.35)
ax2.set_xticks(range(len(AGE_W))); ax2.set_xticklabels(AGE_W)
ax2.set_yticks(range(len(ZIP_D))); ax2.set_yticklabels(ZIP_D)
ax2.set_xlabel("Age bin width"); ax2.set_ylabel("ZIP digits kept"); ax2.set_zlabel("Records at risk")
ax2.set_title("Risk surface with 5% threshold plane")
ax2.view_init(28, -130)

ax3 = fig.add_subplot(2, 3, 3, projection="3d")
xa = res["age_w"].map({v: i for i, v in enumerate(AGE_W)})
yz = res["zip_d"].map({v: i for i, v in enumerate(ZIP_D)})
zi = res["inc_w"].map({v: i for i, v in enumerate(INC_W)})
ok = res["at_risk"] <= RISK_MAX
sc = ax3.scatter(xa[ok], yz[ok], zi[ok], c=res["r2"][ok], cmap="viridis", s=45, marker="o", label="feasible")
ax3.scatter(xa[~ok], yz[~ok], zi[~ok], c="lightgray", s=12, marker="x", label="infeasible")
bi = (AGE_W.index(best.age_w), ZIP_D.index(best.zip_d), INC_W.index(best.inc_w))
ax3.scatter(*bi, c="red", s=250, marker="*", label="optimum")
ax3.set_xticks(range(len(AGE_W))); ax3.set_xticklabels(AGE_W)
ax3.set_yticks(range(len(ZIP_D))); ax3.set_yticklabels(ZIP_D)
ax3.set_zticks(range(len(INC_W))); ax3.set_zticklabels([f"{v//1000}k" for v in INC_W])
ax3.set_xlabel("Age bin width"); ax3.set_ylabel("ZIP digits kept"); ax3.set_zlabel("Income bin")
ax3.set_title("Generalization lattice (color = R²)")
fig.colorbar(sc, ax=ax3, shrink=0.55, pad=0.1)
ax3.legend(loc="upper left", fontsize=8)

ax4 = fig.add_subplot(2, 3, 4)
ax4.scatter(res["at_risk"], res["r2"], c="gray", s=15, alpha=0.6, label="all configs")
ax4.plot(pareto["at_risk"], pareto["r2"], "b-o", ms=4, label="Pareto front")
ax4.axvline(RISK_MAX, color="r", ls="--", label="risk threshold")
ax4.scatter(best.at_risk, best.r2, c="red", s=200, marker="*", zorder=5, label="optimum")
ax4.set_xscale("symlog", linthresh=1e-3)
ax4.set_xlabel("Records at risk (k < 5)"); ax4.set_ylabel("R²")
ax4.set_title("Privacy–utility trade-off"); ax4.legend(fontsize=8); ax4.grid(alpha=0.3)

ax5 = fig.add_subplot(2, 3, 5)
H = np.full((len(AGE_W), len(ZIP_D)), np.nan)
for i, aw in enumerate(AGE_W):
for j, zd in enumerate(ZIP_D):
f = feas[(feas.age_w == aw) & (feas.zip_d == zd)]
if len(f): H[i, j] = f["r2"].max()
im = ax5.imshow(H, cmap="YlGn", aspect="auto")
for i in range(len(AGE_W)):
for j in range(len(ZIP_D)):
ax5.text(j, i, "—" if np.isnan(H[i, j]) else f"{H[i, j]:.3f}", ha="center", va="center", fontsize=8)
ax5.set_xticks(range(len(ZIP_D))); ax5.set_xticklabels(ZIP_D)
ax5.set_yticks(range(len(AGE_W))); ax5.set_yticklabels(AGE_W)
ax5.set_xlabel("ZIP digits kept"); ax5.set_ylabel("Age bin width")
ax5.set_title("Best feasible R² (max over income bins)")
fig.colorbar(im, ax=ax5)

ax6 = fig.add_subplot(2, 3, 6)
_, _, _, s_raw = risk_metrics(*[generalize(1, 5, 1000)[k] for k in (0, 2, 3)])
g = generalize(int(best.age_w), int(best.zip_d), int(best.inc_w))
_, _, _, s_opt = risk_metrics(g[0], g[2], g[3])
bins = np.logspace(0, np.log10(max(s_raw.max(), s_opt.max()) + 1), 40)
ax6.hist(s_raw, bins=bins, alpha=0.6, label="raw", color="tomato")
ax6.hist(s_opt, bins=bins, alpha=0.6, label="optimal", color="seagreen")
ax6.axvline(K, color="k", ls="--", label=f"k = {K}")
ax6.set_xscale("log"); ax6.set_yscale("log")
ax6.set_xlabel("Equivalence class size of each record"); ax6.set_ylabel("Records")
ax6.set_title("Equivalence class size distribution"); ax6.legend(fontsize=8)

plt.tight_layout()
plt.show()

Code Walkthrough

1. Synthetic microdata

We draw 30,000 members with uniform ages from 18 to 89, a binary gender, and a 5-digit ZIP code built from three parts (d1, d2, d345). Income is log-normal and drifts slightly upward with age, so income and age are mildly correlated, as they are in real data.

The cost formula implements the data-generating process above. The term 4.0 * (age - 18) ** 1.6 makes cost rise convexly with age, which is why very wide age bins will hurt. The regional effects state_eff, region_eff and area_eff are indexed by the first one, two and three ZIP digits, so geography matters in layers.

The data is split 70/30 into train and test sets (is_train). Each record also gets a fold index (fold), used later for leakage-free target encoding.

2. Generalization operators

generalize(age_w, zip_d, inc_w) turns one lattice point $\theta$ into masked attributes:

  • a_bin = age // age_w is the integer bin ID, used for risk computation.
  • a_mid is the bin midpoint, the value the analyst would actually see and use in a model.
  • z_pre = zip // 10**(5 - zip_d) keeps only the leading zip_d digits. When zip_d = 0 every record maps to 0, so the ZIP code is fully suppressed.
  • Income gets the same treatment as age.

3. Re-identification risk, computed fast

This is where most of the speed comes from. A naive approach would call df.groupby([age, gender, zip, income]).transform("size") for each of the 216 configurations. Multi-column groupby on DataFrames is slow, because pandas has to hash tuples of mixed types.

Instead, we pack the four quasi-identifiers into a single int64 key with a mixed-radix encoding:

$$
\text{key} = \bigl((a_{\text{bin}} \cdot 100001 + z_{\text{pre}}) \cdot 2 + g\bigr) \cdot 1000 + i_{\text{bin}} .
$$

The multipliers are larger than the range of the next field (ZIP prefix < 100,000, gender ∈ {0, 1}, income bin < 1,000), so the encoding is injective. Two records share a key if and only if they share every quasi-identifier.

Then a single np.unique(key, return_inverse=True, return_counts=True) returns each class’s size, and cnt[inv] maps it back to every record. This runs in $O(N \log N)$ inside compiled NumPy code, and the whole risk evaluation for one configuration takes a few milliseconds.

From the class sizes we compute:

  • at_risk: the share of records with $|E(r)| < 5$
  • avg_risk: the mean of $1/|E(r)|$
  • k_min: the effective $k$ of the release

4. Utility measurement

The analyst’s model is an ordinary least squares regression on features they can build from the released data:

  • A cubic polynomial in the age-bin midpoint, centered and scaled for numerical stability: $\tilde a = (a_{\text{mid}} - 50)/10$, with $\tilde a, \tilde a^2, \tilde a^3$
  • Gender
  • The income-bin midpoint, scaled by $10^4$
  • Hierarchical target encodings of the ZIP prefix, one per retained level $L = 1, \dots, d_z$

ZIP codes are categorical with up to 100,000 levels, so one-hot encoding is out. For each level we replace the prefix with a smoothed mean of the target:

$$
\text{enc}(c) = \frac{\sum_{r \in c} y_r + m,\bar y}{n_c + m}, \qquad m = 20 .
$$

The prior weight $m$ pulls small categories toward the global mean $\bar y$, which prevents overfitting on sparse prefixes.

There is a classic trap here. If a training row’s own $y$ is included when computing its encoding, the feature leaks the target. The model then learns to trust the encoding far too much, and the test $R^2$ collapses. We avoid this with 5-fold out-of-fold encoding. Each training row’s encoding is computed only from the other four folds. Test rows are encoded using the full training set, which is exactly what would happen in production.

Including all levels $1, \dots, d_z$ rather than only the finest one lets the model rely on coarse geography when the fine levels are too sparse to be informative. As a result, keeping more digits never removes information the model could use, and the comparison across configurations is fair.

Finally, np.linalg.lstsq fits the coefficients and we compute the test-set $R^2$.

5. Exhaustive search over the lattice

Three nested loops visit all 216 schemes. For each one we record the risk metrics and the utility. Then we:

  • Use the identity configuration $(1, 5, 1000)$ as the “raw data” baseline
  • Filter for feasibility, $R_{\text{at-risk}} \le 0.05$
  • Pick the feasible scheme with the highest $R^2$, breaking ties by larger $k_{\min}$
  • Compute the Pareto front: sort by risk ascending, then sweep and keep every point whose $R^2$ beats all lower-risk points. Each Pareto point is a scheme that no other scheme beats on both privacy and utility at once.

The full search finishes in a few seconds. Most of that time goes to the target encoding, not the risk computation, so there is no need for a smarter lattice search (such as Incognito or OLA-style pruning) at this scale. With dozens of quasi-identifiers, monotonicity pruning would become worthwhile. If a scheme already satisfies the risk constraint, every coarser scheme does too.

6. Visualization

The figure is a 2×3 grid:

  1. Utility surface (3D): $R^2$ over age bin width × ZIP digits, with income fixed at the optimum’s bin width
  2. Risk surface (3D): the share of records at risk over the same grid, cut by a translucent cyan plane at the 5% threshold
  3. Generalization lattice (3D scatter): all 216 schemes in the space $(w_a, d_z, w_i)$. Feasible ones are colored by $R^2$, infeasible ones are gray crosses, and the optimum is a red star.
  4. Privacy–utility trade-off: $R^2$ against risk on a symlog axis, with the Pareto front and the threshold line
  5. Feasibility heatmap: for each (age, ZIP) pair, the best $R^2$ achievable while meeting the risk budget, maximized over income bins. A dash means no income bin can make that pair feasible.
  6. Equivalence class size distribution: log-log histograms of $|E(r)|$ for the raw data and for the optimal release

Execution Results

Configurations evaluated : 216  (24.16 s)
Raw data   : R2 = 0.7770, records at risk (k<5) = 100.000%
Feasible configurations (risk <= 5%) : 46
Optimal configuration:
  age bin width = 5 years, ZIP digits kept = 1, income bin width = 50,000
  R2 = 0.6231 (80.2% of raw utility)
  records at risk = 1.730%, average risk = 0.0368, k_min = 1

Top 5 feasible configurations:
 age_w  zip_d  inc_w  at_risk  avg_risk  k_min       r2
     5      1  50000 0.017300  0.036767      1 0.623082
    10      1  25000 0.024200  0.037767      1 0.622082
    40      2  50000 0.040967  0.065333      1 0.621828
    10      1  50000 0.009667  0.021133      1 0.615203
    40      2 100000 0.029000  0.039800      1 0.610392


Interpreting the Results

The raw data is a privacy disaster

With all attributes at full resolution, essentially 100% of records are unique. Every record sits in an equivalence class of size 1. You can see this in the bottom-right histogram, where the entire red mass is piled at $|E| = 1$. Releasing this data would give an attacker who knows a neighbor’s age, gender, ZIP and approximate income a near-certain match.

The raw data also gives the best model, with an out-of-sample $R^2$ of roughly 0.78. This is the ceiling against which every anonymized release is judged.

Risk falls off a cliff, not a slope

The risk surface (top middle) is the most instructive plot. Risk does not decrease smoothly with generalization. It stays near 1.0 across most of the grid and then drops sharply only when the ZIP code is cut to 1–2 digits. The reason is combinatorial. With 30,000 records spread over $10^{d_z}$ ZIP prefixes × age bins × income bins × 2 genders, the expected class size is

$$
\mathbb{E}|E| \approx \frac{N}{10^{d_z} \cdot n_a \cdot n_i \cdot 2}.
$$

Equivalence classes reach an average size of 5 only once the denominator falls to roughly 6,000. ZIP code is by far the most identifying attribute, because each extra digit multiplies the number of cells by ten.

Utility degrades gracefully, and unevenly

The utility surface (top left) behaves very differently.

  • Dropping ZIP digits 4–5 costs almost nothing. They carry no signal in the true model, only identifying power. This is the “free lunch” region of anonymization.
  • Dropping digit 3 costs a little, since $\gamma$ has a standard deviation of 400.
  • Dropping digits 1–2 costs a lot, because $\alpha$ and $\beta$ are large regional effects.
  • Age generalization is cheap up to about 10 years. The cubic polynomial fitted on bin midpoints still tracks the convex age curve well. At 40-year bins only about three age groups remain and the curvature is lost.

The optimum

Among the 46 feasible schemes, the winner keeps 5-year age bins, only the first ZIP digit, and 50k income bins. It retains about 80% of the raw utility ($R^2 \approx 0.62$) while only about 1.7% of records remain at risk, well inside the 5% budget.

The runners-up in the console’s top-5 table show that the solution space is quite flat near the top:

  • (10-year age, 1 ZIP digit, 25k income) is within 0.001 in $R^2$.
  • (40-year age, 2 ZIP digits, 50k income) reaches almost the same $R^2$ by a completely different route. It gives up nearly all age detail in exchange for the second ZIP digit and the large regional effect $\beta$.

This second route matters in practice. Two schemes with the same headline utility can serve very different analyses. A geographic health-equity study would prefer the 2-digit ZIP version. An actuarial age-pricing model would prefer the 5-year age version. “Maximize utility” always has to be read as “maximize utility for a specific downstream task”.

The Pareto front shows where to negotiate

The bottom-left plot is the one to bring to a data governance meeting. The Pareto front rises in steps, and each step corresponds to giving up or restoring one ZIP digit:

  • Around $R_{\text{at-risk}} \approx 10^{-3}$, $R^2$ jumps from about 0.5 to about 0.6. That is the gain from keeping the first ZIP digit instead of suppressing ZIP entirely.
  • Just to the right of the 5% line, $R^2$ jumps again to about 0.7. That is the second ZIP digit, which the constraint forbids.

So the key policy question is simply: is a 5% at-risk budget the right one? Relaxing it to around 10% would buy about 0.1 of $R^2$. Tightening it to 0.5% costs only a few hundredths. A plot like this makes the price of every privacy decision explicit, instead of leaving it as an argument between “privacy people” and “data people”.

The heatmap: which combinations can work at all

The feasibility heatmap (bottom middle) shows that keeping 3 or more ZIP digits is never feasible, however coarse age and income become. Two digits work only together with 40-year age bins. Almost all usable releases live in the “1 ZIP digit” column, where the darkest cells (5–10 year age bins) are the sweet spot.

Equivalence class distribution

The bottom-right histogram compares the raw and optimal releases. After optimal generalization, the bulk of records moves into classes of size 30–80, far above $k = 5$. A small tail (the ~1.7% at-risk records) remains below the dashed $k = 5$ line. In a real release these would be handled by local suppression, either masking a cell or dropping the record. Because they are so few, this barely affects utility, which is exactly why the at-risk-share formulation beats strict global $k$-anonymity in practice.


Takeaways

  1. Treat anonymization as constrained optimization. Fix the risk budget $\varepsilon$, define utility as performance on the real downstream task, and search the generalization lattice.
  2. Attributes are not equal. High-cardinality quasi-identifiers such as ZIP code dominate risk, while the signal often sits in their coarse levels. Truncate those aggressively first.
  3. Measure utility honestly. Target encoding without out-of-fold computation leaks the label and can make heavily masked data look better than raw data. That artifact would quietly push you toward the wrong release.
  4. Engineer the risk computation. Packing quasi-identifiers into a single integer key and using np.unique makes evaluating hundreds of schemes on tens of thousands of records nearly instant.
  5. Show the Pareto front, not only the optimum. The threshold is a policy choice, and stakeholders deserve to see what each point of privacy costs in analytical power.

Solving the Least Privilege Problem with Mixed-Integer Linear Programming in Python

The principle of least privilege says that every user should get the permissions their job requires and nothing more. In practice this is hard to do. Permissions are usually handed out through roles: pre-built bundles such as “Finance Viewer” or “DevOps Operator”. These bundles rarely match any one person’s needs exactly. If you assign a role to cover one permission, the user often gets several others they don’t need. Across hundreds of users, those extra permissions add up to a large attack surface.

This article turns the principle of least privilege into an optimization problem, solves it exactly with mixed-integer linear programming (MILP) in Python, and compares the result with the greedy approach that many identity teams use without realizing it.


The Problem Setting

Consider a small organization with:

  • 12 users $u \in \mathcal{U}$
  • 16 permissions $p \in \mathcal{P}$ (e.g., read_payroll, approve_invoice, deploy_prod, …). Each permission has a risk score $w_p \in [1, 10]$.
  • 14 predefined roles $r \in \mathcal{R}$. Each role is a fixed bundle of 2–5 permissions.
  • A need matrix $N_{u,p} \in {0,1}$ that says which permissions each user actually needs.
  • Separation of Duties (SoD) pairs $(a,b) \in \mathcal{S}$: two permissions one person should not hold together, such as “create vendor” and “approve payment”.

There are two ways to grant access:

  1. Role assignment. This is cheap to administer but coarse, so it often brings in extra permissions.
  2. Direct grant of a single permission. This is precise, but every exception has to be documented, reviewed and audited, so it carries an administrative cost $\mu$.

The goal is to find the assignment that guarantees every needed permission while minimizing the total risk of the extra permissions, the administrative overhead and SoD violations.


Mathematical Formulation

Decision variables

$$
x_{u,r} \in {0,1} \quad \text{user } u \text{ is assigned role } r
$$

$$
y_{u,p} \in {0,1} \quad \text{user } u \text{ effectively holds permission } p
$$

$$
d_{u,p} \in {0,1} \quad \text{permission } p \text{ is directly granted to } u \ (\text{allowed only if } N_{u,p}=1)
$$

$$
s_{u,k} \in {0,1} \quad \text{SoD pair } k \text{ is violated for user } u
$$

Objective

$$
\min \quad \lambda \sum_{u}\sum_{r} x_{u,r} ;+; \sum_{u}\sum_{p} w_p, y_{u,p} ;+; \mu \sum_{u}\sum_{p} d_{u,p} ;+; M \sum_{u}\sum_{k} s_{u,k}
$$

  • $\lambda$: administrative cost per role assignment
  • $w_p, y_{u,p}$: risk of every permission held. For needed permissions this term is a constant, so in effect only the risk of the extra permissions is minimized.
  • $\mu$: cost per direct grant
  • $M$: a large penalty for SoD violations, which makes them a near-hard constraint while keeping the model feasible

Constraints

Role propagation. A role grants every permission it contains:

$$
x_{u,r} \le y_{u,p} \qquad \forall u,\ \forall r,\ \forall p : A_{r,p} = 1
$$

Business coverage. Every needed permission must come from at least one role or from a direct grant:

$$
\sum_{r : A_{r,p}=1} x_{u,r} ;+; d_{u,p} ;\ge; 1 \qquad \forall u,\ \forall p : N_{u,p}=1
$$

Direct-grant consistency. A direct grant counts as holding the permission:

$$
d_{u,p} \le y_{u,p}
$$

Separation of Duties (soft). The constraint is skipped when the business explicitly needs both permissions:

$$
y_{u,a} + y_{u,b} - s_{u,k} \le 1 \qquad \forall u,\ \forall k=(a,b)\in\mathcal{S} : \neg(N_{u,a}=1 \wedge N_{u,b}=1)
$$

Optional direct-grant budget, used to trace the trade-off curve:

$$
\sum_{u}\sum_{p} d_{u,p} \le B
$$

When $d \equiv 0$ the model reduces to a weighted set-cover problem, which is NP-hard. The direct-grant extension turns it into a clean trade-off between precision and administrative overhead.


Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import milp, LinearConstraint, Bounds
from scipy.sparse import coo_matrix
import time

rng = np.random.default_rng(42)

U, P, R = 12, 16, 14
perm_names = [f"P{p:02d}" for p in range(P)]
risk = np.round(rng.uniform(1.0, 10.0, P), 1)

roles = np.zeros((R, P), dtype=int)
for r in range(R):
k = rng.integers(2, 6)
roles[r, rng.choice(P, k, replace=False)] = 1
for p in range(P):
if roles[:, p].sum() == 0:
roles[rng.integers(R), p] = 1

need = np.zeros((U, P), dtype=int)
for u in range(U):
k = rng.integers(2, 5)
need[u, rng.choice(P, k, replace=False)] = 1

sod_pairs = [(0, 1), (2, 3), (4, 5), (6, 7)]

def build_and_solve(need, roles, risk, sod_pairs, lam, direct_cost=None, max_direct=None, sod_penalty=100.0):
U, P = need.shape
R = roles.shape[0]
K = len(sod_pairs)
nx, ny, ns, nd = U * R, U * P, U * K, U * P
n = nx + ny + ns + nd
dc = 0.0 if direct_cost is None else direct_cost
c = np.concatenate([np.full(nx, lam), np.tile(risk, U), np.full(ns, sod_penalty), np.full(nd, dc)])
ub = np.ones(n)
if direct_cost is None and max_direct is None:
ub[nx + ny + ns:] = 0
else:
ub[nx + ny + ns:] = need.ravel()
d0 = nx + ny + ns
ri, ci, vi, lo, hi = [], [], [], [], []
k = 0
rr, pp = np.nonzero(roles)
m = len(rr)
for u in range(U):
rows = k + np.arange(m)
ri += [rows, rows]
ci += [u * R + rr, nx + u * P + pp]
vi += [np.ones(m), -np.ones(m)]
lo.append(np.full(m, -np.inf)); hi.append(np.zeros(m)); k += m
for p in np.flatnonzero(need[u]):
ri.append(np.array([k, k])); ci.append(np.array([d0 + u * P + p, nx + u * P + p]))
vi.append(np.array([1.0, -1.0]))
lo.append(np.array([-np.inf])); hi.append(np.array([0.0])); k += 1
cov = np.flatnonzero(roles[:, p])
ri.append(np.full(len(cov) + 1, k))
ci.append(np.append(u * R + cov, d0 + u * P + p))
vi.append(np.ones(len(cov) + 1))
lo.append(np.array([1.0])); hi.append(np.array([np.inf])); k += 1
for j, (a, b) in enumerate(sod_pairs):
if need[u, a] and need[u, b]:
continue
ri.append(np.full(3, k))
ci.append(np.array([nx + u * P + a, nx + u * P + b, nx + ny + u * K + j]))
vi.append(np.array([1.0, 1.0, -1.0]))
lo.append(np.array([-np.inf])); hi.append(np.array([1.0])); k += 1
if max_direct is not None:
ri.append(np.full(nd, k)); ci.append(d0 + np.arange(nd)); vi.append(np.ones(nd))
lo.append(np.array([-np.inf])); hi.append(np.array([float(max_direct)])); k += 1
A = coo_matrix((np.concatenate(vi), (np.concatenate(ri), np.concatenate(ci))), shape=(k, n)).tocsr()
res = milp(c, constraints=LinearConstraint(A, np.concatenate(lo), np.concatenate(hi)),
integrality=np.ones(n), bounds=Bounds(np.zeros(n), ub),
options={"time_limit": 60})
if res.x is None:
return None
z = np.round(res.x).astype(int)
X = z[:nx].reshape(U, R)
Y = z[nx:nx + ny].reshape(U, P)
D = z[d0:].reshape(U, P)
return X, Y, D, res.fun

def greedy(need, roles, risk):
U, P = need.shape
X = np.zeros((U, roles.shape[0]), dtype=int)
for u in range(U):
left = need[u].copy()
while left.sum() > 0:
gain = roles @ left
gain = np.where(gain > 0, gain, 0)
r = int(np.argmax(gain))
X[u, r] = 1
left = left * (1 - roles[r])
Y = (X @ roles > 0).astype(int)
return X, Y

lam = 2.0
mu = 12.0
X_rb, Y_rb, _, obj_rb = build_and_solve(need, roles, risk, sod_pairs, lam)
X_opt, Y_opt, D_opt, obj = build_and_solve(need, roles, risk, sod_pairs, lam, direct_cost=mu)
X_gr, Y_gr = greedy(need, roles, risk)

def excess(Y):
return ((Y - need).clip(0) * risk).sum(axis=1)

def sod_viol(Y):
v = 0
for u in range(U):
for a, b in sod_pairs:
if Y[u, a] and Y[u, b] and not (need[u, a] and need[u, b]):
v += 1
return v

print("=== Least Privilege Optimization ===")
print(f"Users={U}, Permissions={P}, Roles={R}, lambda={lam}, mu={mu}")
print(f"{'':26s}{'Greedy':>10s}{'MILP-RBAC':>12s}{'MILP+Direct':>13s}")
print(f"{'Coverage OK':26s}{str(bool(np.all(Y_gr >= need))):>10s}{str(bool(np.all(Y_rb >= need))):>12s}{str(bool(np.all(Y_opt >= need))):>13s}")
print(f"{'Excess risk':26s}{excess(Y_gr).sum():10.1f}{excess(Y_rb).sum():12.1f}{excess(Y_opt).sum():13.1f}")
print(f"{'Excess permissions':26s}{int((Y_gr - need).clip(0).sum()):10d}{int((Y_rb - need).clip(0).sum()):12d}{int((Y_opt - need).clip(0).sum()):13d}")
print(f"{'Role assignments':26s}{int(X_gr.sum()):10d}{int(X_rb.sum()):12d}{int(X_opt.sum()):13d}")
print(f"{'Direct grants':26s}{0:10d}{0:12d}{int(D_opt.sum()):13d}")
print(f"{'SoD violations':26s}{sod_viol(Y_gr):10d}{sod_viol(Y_rb):12d}{sod_viol(Y_opt):13d}")
print(f"Objective (MILP+Direct) : {obj:.2f}")
print()
for u in range(U):
rs = ",".join(f"R{r}" for r in np.flatnonzero(X_opt[u]))
ds = ",".join(perm_names[p] for p in np.flatnonzero(D_opt[u]))
ex = ",".join(perm_names[p] for p in np.flatnonzero(Y_opt[u] & (1 - need[u])))
print(f"User{u:02d}: roles=[{rs}] direct=[{ds}] excess=[{ex}]")

budgets = np.arange(0, 21, 2)
pareto_risk, pareto_sod = [], []
for B in budgets:
Xb, Yb, Db, _ = build_and_solve(need, roles, risk, sod_pairs, lam, max_direct=int(B))
pareto_risk.append(excess(Yb).sum())
pareto_sod.append(sod_viol(Yb))
print()
print("DirectBudget ExcessRisk SoDViolations")
for B, rk, sv in zip(budgets, pareto_risk, pareto_sod):
print(f"{B:12d} {rk:10.1f} {sv:13d}")

sizes = [20, 50, 100, 150, 200]
scales = [0.5, 1.0, 1.5, 2.0]
T = np.zeros((len(scales), len(sizes)))
for i, s in enumerate(scales):
for j, nu in enumerate(sizes):
r2 = np.random.default_rng(100 + i * 10 + j)
P2, R2 = int(16 * s), int(10 * s)
ro = np.zeros((R2, P2), dtype=int)
for r in range(R2):
ro[r, r2.choice(P2, r2.integers(2, 6), replace=False)] = 1
for p in range(P2):
if ro[:, p].sum() == 0:
ro[r2.integers(R2), p] = 1
ne = np.zeros((nu, P2), dtype=int)
for u in range(nu):
ne[u, r2.choice(P2, r2.integers(2, 5), replace=False)] = 1
rk = r2.uniform(1, 10, P2)
ts = []
for _ in range(3):
t0 = time.perf_counter()
build_and_solve(ne, ro, rk, [], lam, direct_cost=mu)
ts.append(time.perf_counter() - t0)
T[i, j] = min(ts)
print()
print("Solve time [s] (rows=scale, cols=users):")
print(np.round(T, 3))

fig = plt.figure(figsize=(21, 12))

ax1 = fig.add_subplot(2, 3, 1)
state = np.where(D_opt == 1, 3, np.where(need == 1, 2, Y_opt))
cmap = matplotlib.colors.ListedColormap(["#f2f2f2", "#ff7f0e", "#2ca02c", "#1f77b4"])
ax1.imshow(state, cmap=cmap, vmin=-0.5, vmax=3.5, aspect="auto")
ax1.set_xticks(range(P)); ax1.set_xticklabels(perm_names, rotation=90, fontsize=8)
ax1.set_yticks(range(U)); ax1.set_yticklabels([f"U{u:02d}" for u in range(U)], fontsize=8)
ax1.set_title("Optimal grants (green=role, blue=direct, orange=excess)")

ax2 = fig.add_subplot(2, 3, 2)
idx = np.arange(U); w = 0.38
w3 = 0.27
ax2.bar(idx - w3, excess(Y_gr), w3, label="Greedy", color="#d62728")
ax2.bar(idx, excess(Y_rb), w3, label="MILP-RBAC", color="#ff7f0e")
ax2.bar(idx + w3, excess(Y_opt), w3, label="MILP+Direct", color="#1f77b4")
ax2.set_xticks(idx); ax2.set_xticklabels([f"U{u:02d}" for u in range(U)], rotation=90, fontsize=8)
ax2.set_ylabel("Excess risk"); ax2.set_title("Excess privilege risk per user"); ax2.legend()

ax3 = fig.add_subplot(2, 3, 3)
ax3.plot(budgets, pareto_risk, "o-", color="#9467bd", label="Excess risk")
ax3.axvline(D_opt.sum(), color="gray", ls="--", label=f"Chosen (mu={mu:g}): {int(D_opt.sum())} direct grants")
ax3b = ax3.twinx()
ax3b.step(budgets, pareto_sod, where="mid", color="#e377c2", alpha=0.7)
ax3b.set_ylabel("SoD violations", color="#e377c2")
ax3.legend(loc="upper right")
ax3.set_xlabel("Max number of direct grants"); ax3.set_ylabel("Total excess risk")
ax3.set_title("Trade-off: direct-grant budget vs excess risk"); ax3.grid(alpha=0.3)

ax4 = fig.add_subplot(2, 3, 4, projection="3d")
uu, pp = np.meshgrid(np.arange(U), np.arange(P), indexing="ij")
hz = (Y_opt * risk).ravel()
col = np.where(D_opt.ravel() == 1, "#1f77b4", np.where((need == 1).ravel(), "#2ca02c", "#ff7f0e"))
m = hz > 0
ax4.bar3d(uu.ravel()[m], pp.ravel()[m], np.zeros(m.sum()), 0.7, 0.7, hz[m], color=col[m], shade=True)
ax4.set_xlabel("User"); ax4.set_ylabel("Permission"); ax4.set_zlabel("Risk")
ax4.set_title("3D: granted permissions weighted by risk")

ax5 = fig.add_subplot(2, 3, 5, projection="3d")
S, N = np.meshgrid(np.array(sizes), np.array(scales) * 16)
ax5.plot_surface(S, N, T, cmap="viridis", edgecolor="k", linewidth=0.3)
ax5.set_xlabel("Users"); ax5.set_ylabel("Permissions"); ax5.set_zlabel("Time [s]")
ax5.set_title("3D: MILP solve time scaling")

ax6 = fig.add_subplot(2, 3, 6)
ax6.bar(np.arange(R) - w3, X_gr.sum(axis=0), w3, label="Greedy", color="#d62728")
ax6.bar(np.arange(R), X_rb.sum(axis=0), w3, label="MILP-RBAC", color="#ff7f0e")
ax6.bar(np.arange(R) + w3, X_opt.sum(axis=0), w3, label="MILP+Direct", color="#1f77b4")
ax6.set_xticks(range(R)); ax6.set_xticklabels([f"R{r}" for r in range(R)])
ax6.set_ylabel("Users assigned"); ax6.set_title("Role usage"); ax6.legend()

plt.tight_layout()
plt.show()

Code Walkthrough

1. Generating the example data

A fixed random seed (default_rng(42)) makes the example reproducible.

  • risk: a risk score $w_p$ between 1.0 and 10.0 for each permission.
  • roles: the $R \times P$ role–permission matrix $A_{r,p}$. Each role gets 2–5 random permissions. A safety loop then makes sure every permission belongs to at least one role, so the pure role-based model always has a feasible solution.
  • need: the $U \times P$ need matrix $N_{u,p}$. Each user needs 2–4 permissions.
  • sod_pairs: four conflicting pairs, e.g. (P00, P01) could be “create vendor” and “approve payment”.

2. build_and_solve: building the MILP

This function is the core of the article. All variables sit in one flat vector in this order:

Block Size Meaning
x $U\cdot R$ role assignments
y $U\cdot P$ effective permissions
s $U\cdot K$ SoD violation slacks
d $U\cdot P$ direct grants

The cost vector c matches the objective term by term: $\lambda$ for each x, $w_p$ for each y, the penalty $M=100$ for each s, and $\mu$ for each d.

Upper bounds as a modeling trick. The ub array sets the upper bound of $d_{u,p}$ to $N_{u,p}$. A direct grant is therefore possible only for permissions the user actually needs, and no extra constraints are required for this. When neither direct_cost nor max_direct is given, all d bounds are 0, which gives the pure RBAC model (MILP-RBAC).

Building the sparse matrix (the speed-up). The constraint matrix is filled as COO triplets (ri, ci, vi) and converted to CSR only once. The role-propagation block is the largest one, with $U \cdot \text{nnz}(A)$ rows. It is created for each user with one vectorized operation on the precomputed role–permission pairs rr, pp = np.nonzero(roles), not with nested Python loops. An earlier version that set entries one at a time in a lil_matrix got slower in proportion to the number of nonzeros. The vectorized COO version spends almost all of its time inside the HiGHS solver, not in Python.

The constraints, in order:

  1. Propagation $x_{u,r} - y_{u,p} \le 0$: one row per user and per (role, permission) pair.
  2. Direct-grant consistency $d_{u,p} - y_{u,p} \le 0$.
  3. Coverage $\sum_r x_{u,r} + d_{u,p} \ge 1$, which uses every role that contains $p$.
  4. SoD $y_{u,a} + y_{u,b} - s_{u,k} \le 1$, skipped when the user needs both permissions.
  5. Optional budget $\sum d \le B$, used for the trade-off curve.

scipy.optimize.milp calls the HiGHS branch-and-cut solver. integrality=np.ones(n) makes every variable binary, together with the [0, ub] bounds. The solution is rounded to clean integers and split back into the X, Y and D matrices.

3. greedy: the baseline

This mirrors what an administrator does by hand. For each user, it repeatedly picks the role that covers the most still-uncovered needed permissions until everything is covered. It ignores risk scores and SoD rules entirely. This is the classic $\ln n$-approximation for set cover.

4. Three strategies compared

  • Greedy: the heuristic role assignment.
  • MILP-RBAC: the optimal assignment using roles only ($d \equiv 0$).
  • MILP+Direct: the optimal assignment where direct grants cost $\mu = 12$ each.

excess(Y) computes each user’s extra-permission risk $\sum_p w_p \max(0, Y_{u,p} - N_{u,p})$. sod_viol(Y) counts real SoD conflicts.

5. Trade-off sweep

The model is solved again with a hard cap $B \in {0, 2, \dots, 20}$ on the number of direct grants. This traces the efficient frontier: how much extra-permission risk you can remove for each additional exception you are willing to manage.

6. Scalability experiment

Random instances are generated with 20–200 users and 8–32 permissions (with matching role counts). Each instance is solved three times and the minimum wall-clock time is kept, which filters out timing noise from the shared Colab machine.

7. Visualization

A single 21 × 12 figure holds a 2 × 3 grid. The panels are explained in the next section.


Execution Results

=== Least Privilege Optimization ===
Users=12, Permissions=16, Roles=14, lambda=2.0, mu=12.0
                              Greedy   MILP-RBAC  MILP+Direct
Coverage OK                     True        True         True
Excess risk                    387.6       251.8         85.4
Excess permissions                59          39           17
Role assignments                  27          26           18
Direct grants                      0           0           11
SoD violations                    12           3            0
Objective (MILP+Direct)   : 453.10

User00: roles=[R8]  direct=[P06,P09]  excess=[P04]
User01: roles=[R0,R10]  direct=[]  excess=[P10]
User02: roles=[R4]  direct=[P00,P03]  excess=[P11,P12]
User03: roles=[R10]  direct=[P06]  excess=[P10]
User04: roles=[]  direct=[P03,P13]  excess=[]
User05: roles=[R5,R8]  direct=[]  excess=[P00,P11]
User06: roles=[R0,R10]  direct=[]  excess=[P08]
User07: roles=[R8,R11]  direct=[]  excess=[P00,P10,P12]
User08: roles=[R8]  direct=[P01]  excess=[P04]
User09: roles=[R0,R10]  direct=[P02,P06]  excess=[P08,P15]
User10: roles=[R10,R12]  direct=[P09]  excess=[P08,P10]
User11: roles=[R7,R8]  direct=[]  excess=[P12]

DirectBudget  ExcessRisk  SoDViolations
           0       251.8              3
           2       210.8              1
           4       201.1              0
           6       154.2              0
           8       124.7              0
          10        96.8              0
          12        74.3              0
          14        57.0              0
          16        44.7              0
          18        32.9              0
          20        24.3              0

Solve time [s] (rows=scale, cols=users):
[[0.025 0.081 0.072 0.244 0.945]
 [0.024 0.099 0.273 0.402 0.447]
 [0.015 0.068 0.154 0.347 0.398]
 [0.037 0.109 0.208 0.566 0.657]]


Interpreting the Results

Summary table

With the fixed seed, the three strategies compare as follows:

Metric Greedy MILP-RBAC MILP+Direct
Coverage of needed permissions ✓ ✓ ✓
Total extra-permission risk 387.6 251.8 85.4
Extra permissions 59 39 17
Role assignments 27 26 18
Direct grants 0 0 11
SoD violations 12 3 0

All three meet every business need, but at very different cost to security:

  • Optimizing only the choice of roles (MILP-RBAC) already cuts extra-permission risk by about 35 % compared with greedy. It also brings SoD conflicts down from 12 to 3, with no change to the role catalog.
  • Allowing a small number of targeted exceptions (11 direct grants) removes about 78 % of greedy’s extra-permission risk and all SoD violations.

The 3 SoD violations left in MILP-RBAC are unavoidable with the current role catalog. The penalty $M = 100$ is far larger than any risk score, so the solver drives violations to the lowest number possible. A remaining violation therefore tells you that a role needs to be split, which is useful input for role engineering.

Panel 1: Optimal grants heatmap (top left)

Each row is a user and each column is a permission. Green cells are needed permissions covered by a role, blue cells are needed permissions given as direct grants, and orange cells are extra permissions that come in with a role. The goal is as little orange as possible. Columns like P10 and P12 stay orange for several users. These permissions are bundled into popular roles, which makes them strong candidates for splitting those roles.

Panel 2: Extra-permission risk per user (top center)

Red bars are greedy, orange bars are MILP-RBAC and blue bars are MILP+Direct. For users such as U02, U10 and U11, the greedy heuristic grants almost 6× more risk than needed. In a few cases (U00, U03, U09) the RBAC optimum gives a user slightly more risk than greedy. This is expected: the MILP minimizes total risk plus SoD penalties across the organization, so it may accept a little more exposure for one user to remove a serious SoD conflict for another.

Panel 3: Direct-grant budget vs. extra-permission risk (top right)

This is the efficient frontier. The purple curve shows how total extra-permission risk falls as you allow more direct grants. It drops from 251.8 with no exceptions to 24.3 with 20. The pink step line (right axis) shows SoD violations reaching 0 after just 4 exceptions. The curve flattens as it goes, so the first few exceptions are worth the most. The dashed line marks the solution chosen automatically with $\mu = 12$ (11 direct grants), where one more exception would cost more in administration than the risk it removes. Security teams can use this chart to set an exception budget based on data rather than intuition.

Panel 4: 3D view of granted permissions weighted by risk (bottom left)

Every bar is one permission held by one user, and its height is the permission’s risk $w_p$. Green and blue bars are needed permissions; orange bars are extra ones. The 3D view makes it easy to spot tall orange towers: high-risk extra permissions, which are exactly what an attacker would target after compromising that account. These are the first items to fix in an access review.

Panel 5: 3D surface of MILP solve time (bottom center)

Solve time is plotted against the number of users and permissions. Even the largest instance (200 users × 32 permissions, more than 10,000 binary variables) solves in well under a second. The surface is not perfectly smooth, which is typical of branch-and-bound: some instances happen to be harder than others of the same size. Still, the trend shows that exact optimization is entirely practical at department scale. For organizations with tens of thousands of identities, the model splits naturally by user, because users interact only through shared role definitions. Each business unit can then be solved in parallel.

Panel 6: Role usage (bottom right)

This panel shows how many users each strategy assigns to each role. Greedy relies heavily on broad roles such as R1, R2 and R3 because they cover many permissions at once, and that same breadth makes them dangerous. The MILP strategies move toward narrower roles such as R8 and R10. R13 is never used by any strategy, which suggests it can be retired from the catalog.


Key Takeaways

  1. Least privilege can be written as a clear mathematical model. It is a weighted set-cover problem with propagation, coverage and SoD constraints, and modern MILP solvers handle it easily.
  2. Greedy role assignment is costly. Even without changing a single role definition, optimal assignment cut extra-permission risk by about a third and SoD conflicts by three quarters.
  3. Exceptions are a resource to spend, not a failure. The efficient frontier shows exactly how much risk each additional direct grant removes, so you can decide on an exception budget with evidence.
  4. The model points to role-engineering work. SoD violations that remain, permissions that are often extra, and roles nobody uses are concrete signs of which roles to split, narrow or retire.

Optimizing Cyber Insurance Coverage and Premiums

Deductible, Limit and Residual Risk in Python

Buying cyber insurance means choosing three numbers at once: the deductible you absorb yourself, the coverage limit the insurer will pay, and the premium you can afford. A low deductible and a high limit feel safe, but the premium rises quickly. A high deductible keeps the bill small but leaves you exposed to a bad year. This article turns that tension into an optimization problem and solves it in Python.

1. The Example Problem

A mid-sized company faces the following cyber risk profile (all amounts in million USD).

  • Incidents per year follow a Poisson distribution with mean $\lambda = 1.2$.
  • Each incident causes a loss $X$ that follows a heavy-tailed lognormal distribution, $\ln X \sim \mathcal{N}(\mu, \sigma^2)$ with $\mu=\ln 0.5$ and $\sigma = 1.5$.
  • The expected annual loss without insurance is about 1.84 M$, but a bad year can cost many times that.

The company can buy a per-incident policy with deductible $d$ and limit $L$. For one incident, the insurer pays

$$
I(X; d, L) = \min{(X-d)^+,; L},
$$

and the company keeps

$$
R(X; d, L) = X - I(X; d, L).
$$

Over a year, with $N \sim \mathrm{Poisson}(\lambda)$ incidents,

$$
S_{\text{pay}} = \sum_{i=1}^{N} I(X_i; d, L), \qquad S_{\text{ret}} = \sum_{i=1}^{N} R(X_i; d, L).
$$

The insurer prices the policy with an expected-value loading, a volatility loading and a capital charge on the limit:

$$
P(d, L) = (1+\theta),\mathbb{E}[S_{\text{pay}}] + \gamma,\mathrm{SD}[S_{\text{pay}}] + c,L + f,
$$

with $\theta = 0.30$, $\gamma = 0.20$, $c = 0.015$ and $f = 0.05$.

The total annual cost to the company is the premium plus the retained loss:

$$
C = P(d, L) + S_{\text{ret}}.
$$

Residual risk is measured by the Conditional Value at Risk. By the Rockafellar–Uryasev representation,

which is the average cost over the worst $(1-\alpha)$ fraction of years. Financial impact is measured by the probability that the annual cost exceeds a cash buffer $W = 8$ M$:

$$
\Pr(C > W).
$$

The optimization problem balances average cost against tail cost under a premium budget $B = 1.8$ M$:

$$
\min_{d,,L}; J(d, L) = (1-\rho),\mathbb{E}[C] + \rho,\mathrm{CVaR}_{0.95}(C)
\quad \text{s.t.} \quad P(d, L) \le B,;; 0 \le d \le 4,;; 0 < L \le 30,
$$

with risk weight $\rho = 0.5$.

For a lognormal severity, the expected annual payout has a closed form through the limited expected value $\mathrm{LEV}(u) = \mathbb{E}[\min(X, u)]$:

$$
\mathrm{LEV}(u) = e^{\mu + \sigma^2/2},\Phi!\left(\frac{\ln u - \mu - \sigma^2}{\sigma}\right) + u\left[1 - \Phi!\left(\frac{\ln u - \mu}{\sigma}\right)\right],
$$

$$
\mathbb{E}[S_{\text{pay}}] = \lambda,\big[\mathrm{LEV}(d+L) - \mathrm{LEV}(d)\big].
$$

The code uses this formula to validate the simulation.

2. Full Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import time
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import ndtr

# ------------------------------------------------------------------
# 1. Model parameters (monetary unit: million USD)
# ------------------------------------------------------------------
SEED = 2026
N_YEARS = 40_000 # simulated years (scenario set)
LAMBDA = 1.2 # expected number of cyber incidents per year
MU = np.log(0.5) # log-median of incident loss = 0.5 M$
SIGMA = 1.5 # log-standard deviation (heavy tail)
THETA = 0.30 # proportional loading
GAMMA = 0.20 # volatility loading (std of annual payout)
CAP_CHARGE = 0.015 # capital charge per unit of limit
FIXED_FEE = 0.05 # fixed underwriting expense
ALPHA = 0.95 # CVaR confidence level
RHO = 0.50 # weight on tail risk in the objective
BUDGET = 1.80 # maximum premium the company can pay
BUFFER = 8.0 # cash buffer used to measure financial distress
D_MAX = 4.0 # largest deductible considered
L_MAX = 30.0 # largest coverage limit considered

# ------------------------------------------------------------------
# 2. Common-random-number scenario set
# ------------------------------------------------------------------
rng = np.random.default_rng(SEED)
counts = rng.poisson(LAMBDA, N_YEARS)
year_idx = np.repeat(np.arange(N_YEARS), counts)
severity = np.exp(MU + SIGMA * rng.standard_normal(int(counts.sum())))

def annual_sum(event_values):
return np.bincount(year_idx, weights=event_values, minlength=N_YEARS)

def cvar(x, alpha=ALPHA):
k = int(np.ceil((1.0 - alpha) * x.size))
return float(np.partition(x, x.size - k)[x.size - k:].mean())

def lev(u):
u = np.maximum(u, 1e-12)
z = (np.log(u) - MU) / SIGMA
return np.exp(MU + 0.5 * SIGMA ** 2) * ndtr(z - SIGMA) + u * (1.0 - ndtr(z))

def expected_payout_analytic(d, L):
return float(LAMBDA * (lev(d + L) - lev(d)))

def evaluate(d, L, insured=True):
if insured:
payout = np.clip(severity - d, 0.0, L)
annual_pay = annual_sum(payout)
premium = float((1.0 + THETA) * annual_pay.mean() + GAMMA * annual_pay.std()
+ CAP_CHARGE * L + FIXED_FEE)
retained = annual_sum(severity - payout)
exp_payout = float(annual_pay.mean())
else:
premium = 0.0
retained = annual_sum(severity)
exp_payout = 0.0
total = premium + retained
return {
"d": d, "L": L,
"premium": premium,
"exp_payout": exp_payout,
"exp_retained": float(retained.mean()),
"cvar_retained": cvar(retained),
"exp_total": float(total.mean()),
"var_total": float(np.quantile(total, ALPHA)),
"cvar_total": cvar(total),
"p_exceed": float((total > BUFFER).mean()),
"total": total,
}

def objective(res):
return (1.0 - RHO) * res["exp_total"] + RHO * res["cvar_total"]

# ------------------------------------------------------------------
# 3. Stage 1: coarse grid search
# ------------------------------------------------------------------
t0 = time.time()
d_grid = np.linspace(0.05, D_MAX, 30)
L_grid = np.linspace(1.0, L_MAX, 30)
J = np.zeros((d_grid.size, L_grid.size))
P = np.zeros_like(J)
CVR = np.zeros_like(J)
for i, d in enumerate(d_grid):
for j, L in enumerate(L_grid):
r = evaluate(d, L)
J[i, j] = objective(r)
P[i, j] = r["premium"]
CVR[i, j] = r["cvar_retained"]
t_grid = time.time() - t0

feasible = P <= BUDGET
J_feasible = np.where(feasible, J, np.inf)
i_best, j_best = np.unravel_index(np.argmin(J_feasible), J.shape)
i_free, j_free = np.unravel_index(np.argmin(J), J.shape)

# ------------------------------------------------------------------
# 4. Stage 2: zoom-in refinement around the best feasible cell
# ------------------------------------------------------------------
best_d, best_L = float(d_grid[i_best]), float(L_grid[j_best])
best_J = float(J_feasible[i_best, j_best])
half_d = float(d_grid[1] - d_grid[0])
half_L = float(L_grid[1] - L_grid[0])
for _ in range(2):
for d in np.clip(np.linspace(best_d - half_d, best_d + half_d, 15), 0.0, D_MAX):
for L in np.clip(np.linspace(best_L - half_L, best_L + half_L, 15), 0.5, L_MAX):
r = evaluate(float(d), float(L))
if r["premium"] <= BUDGET:
j_val = objective(r)
if j_val < best_J:
best_J, best_d, best_L = j_val, float(d), float(L)
half_d /= 4.0
half_L /= 4.0
t_total = time.time() - t0

res_opt = evaluate(best_d, best_L)
res_free = evaluate(float(d_grid[i_free]), float(L_grid[j_free]))
strategies = [
("No insurance", evaluate(0.0, 0.0, insured=False)),
("Conventional", evaluate(0.5, 10.0)),
("Full cover", evaluate(0.05, 30.0)),
("Optimal (budget)", res_opt),
]

# ------------------------------------------------------------------
# 5. Console report
# ------------------------------------------------------------------
print("=" * 100)
print("Cyber insurance optimization: deductible d, limit L, premium")
print("=" * 100)
print(f"Scenario set: {N_YEARS:,} years, {len(severity):,} incidents")
print(f"Expected annual loss without insurance : {strategies[0][1]['exp_retained']:.3f} M$")
print(f"Grid evaluations: {d_grid.size * L_grid.size} in {t_grid:.2f} s (total with refinement {t_total:.2f} s)")
print(f"Premium budget: {BUDGET:.2f} M$ | Cash buffer: {BUFFER:.1f} M$ | CVaR level: {ALPHA:.0%} | rho = {RHO:.2f}")
print("-" * 100)
print(f"Unconstrained optimum : d = {res_free['d']:.3f}, L = {res_free['L']:.2f}, "
f"premium = {res_free['premium']:.3f}, J = {objective(res_free):.3f}")
print(f"Budget-constrained opt: d = {res_opt['d']:.3f}, L = {res_opt['L']:.2f}, "
f"premium = {res_opt['premium']:.3f}, J = {objective(res_opt):.3f}")
print("-" * 100)
header = (f"{'Strategy':<18}{'d':>6}{'L':>7}{'Premium':>9}{'E[Ret]':>8}{'CVaR[Ret]':>10}"
f"{'E[Cost]':>9}{'VaR95':>8}{'CVaR95':>8}{'P(C>Buf)':>10}{'J':>8}")
print(header)
for name, r in strategies:
print(f"{name:<18}{r['d']:>6.2f}{r['L']:>7.2f}{r['premium']:>9.3f}{r['exp_retained']:>8.3f}"
f"{r['cvar_retained']:>10.3f}{r['exp_total']:>9.3f}{r['var_total']:>8.3f}"
f"{r['cvar_total']:>8.3f}{r['p_exceed']:>10.4f}{objective(r):>8.3f}")
print("-" * 100)
print("Validation of the simulated expected payout against the closed-form lognormal formula")
for name, r in strategies[1:]:
ana = expected_payout_analytic(r["d"], r["L"])
print(f"{name:<18} simulated = {r['exp_payout']:.4f} M$ | analytic = {ana:.4f} M$ | "
f"relative gap = {abs(r['exp_payout'] - ana) / ana:.2%}")
print("=" * 100)

# ------------------------------------------------------------------
# 6. Visualization: 2 rows x 3 columns in one figure
# ------------------------------------------------------------------
plt.style.use("dark_background")
Dm, Lm = np.meshgrid(d_grid, L_grid, indexing="ij")
colors = ["#ff6b6b", "#feca57", "#48dbfb", "#1dd1a1"]

fig = plt.figure(figsize=(22, 12))
fig.suptitle("Cyber Insurance Optimization: Deductible, Coverage Limit and Premium", fontsize=18)

# (1) 3D surface of the objective
ax1 = fig.add_subplot(2, 3, 1, projection="3d")
ax1.plot_surface(Dm, Lm, J, cmap="viridis", alpha=0.92, linewidth=0, antialiased=True)
ax1.scatter([res_opt["d"]], [res_opt["L"]], [objective(res_opt)], color="red", s=90, depthshade=False)
ax1.set_xlabel("Deductible d [M$]")
ax1.set_ylabel("Limit L [M$]")
ax1.set_zlabel("Objective J")
ax1.set_title("(1) Objective surface J(d, L)")
ax1.view_init(elev=28, azim=-125)

# (2) 3D surface of the premium with the budget plane
ax2 = fig.add_subplot(2, 3, 2, projection="3d")
ax2.plot_surface(Dm, Lm, P, cmap="magma", alpha=0.92, linewidth=0, antialiased=True)
ax2.plot_surface(Dm, Lm, np.full_like(P, BUDGET), color="cyan", alpha=0.30, linewidth=0)
ax2.scatter([res_opt["d"]], [res_opt["L"]], [res_opt["premium"]], color="lime", s=90, depthshade=False)
ax2.set_xlabel("Deductible d [M$]")
ax2.set_ylabel("Limit L [M$]")
ax2.set_zlabel("Premium [M$]")
ax2.set_title("(2) Premium surface and budget plane")
ax2.view_init(elev=28, azim=-45)

# (3) Contour map with the feasible region boundary
ax3 = fig.add_subplot(2, 3, 3)
cf = ax3.contourf(d_grid, L_grid, J.T, levels=28, cmap="viridis")
fig.colorbar(cf, ax=ax3, label="Objective J")
ax3.contour(d_grid, L_grid, P.T, levels=[BUDGET], colors="white", linewidths=2.2)
ax3.scatter([res_opt["d"]], [res_opt["L"]], marker="*", s=380, color="red", edgecolor="white",
label="Budget-constrained optimum", zorder=5)
ax3.scatter([res_free["d"]], [res_free["L"]], marker="D", s=110, color="cyan", edgecolor="white",
label="Unconstrained optimum", zorder=5)
ax3.plot([], [], color="white", linewidth=2.2, label="Premium = budget")
ax3.set_xlabel("Deductible d [M$]")
ax3.set_ylabel("Limit L [M$]")
ax3.set_title("(3) Contour of J and feasible region")
ax3.legend(loc="upper right", fontsize=8)

# (4) Premium versus residual tail risk
ax4 = fig.add_subplot(2, 3, 4)
sc = ax4.scatter(P.ravel(), CVR.ravel(), c=Dm.ravel(), cmap="plasma", s=14, alpha=0.9)
fig.colorbar(sc, ax=ax4, label="Deductible d [M$]")
ax4.scatter([0.0], [strategies[0][1]["cvar_retained"]], marker="X", s=160, color="white", label="No insurance")
ax4.scatter([res_opt["premium"]], [res_opt["cvar_retained"]], marker="*", s=380, color="red",
edgecolor="white", label="Optimal", zorder=5)
ax4.axvline(BUDGET, color="cyan", linestyle="--", linewidth=1.5, label="Premium budget")
ax4.set_xlabel("Annual premium [M$]")
ax4.set_ylabel("Residual tail loss: CVaR95 of retained loss [M$]")
ax4.set_title("(4) Premium vs residual risk")
ax4.legend(fontsize=8)
ax4.grid(alpha=0.25)

# (5) Exceedance probability curves of the annual total cost
ax5 = fig.add_subplot(2, 3, 5)
probs = np.logspace(-3, 0, 160)
for (name, r), c in zip(strategies, colors):
ax5.plot(np.quantile(r["total"], 1.0 - probs), probs, color=c, linewidth=2.2, label=name)
ax5.axvline(BUFFER, color="white", linestyle="--", linewidth=1.5, label="Cash buffer")
ax5.set_yscale("log")
ax5.set_xlim(0, 25)
ax5.set_xlabel("Annual total cost: premium + retained loss [M$]")
ax5.set_ylabel("Exceedance probability")
ax5.set_title("(5) Exceedance curves")
ax5.legend(fontsize=8)
ax5.grid(alpha=0.25, which="both")

# (6) Expected cost breakdown and tail cost
ax6 = fig.add_subplot(2, 3, 6)
labels = ["No\ninsurance", "Conventional", "Full\ncover", "Optimal"]
prem = np.array([r["premium"] for _, r in strategies])
ret = np.array([r["exp_retained"] for _, r in strategies])
cv = np.array([r["cvar_total"] for _, r in strategies])
xpos = np.arange(len(strategies))
ax6.bar(xpos, prem, color="#54a0ff", label="Premium")
ax6.bar(xpos, ret, bottom=prem, color="#ff9f43", label="Expected retained loss")
ax6.scatter(xpos, cv, marker="D", s=90, color="#ff6b6b", edgecolor="white", label="CVaR95 of total cost", zorder=5)
ax6.set_xticks(xpos)
ax6.set_xticklabels(labels)
ax6.set_ylabel("Cost [M$]")
ax6.set_title("(6) Expected cost breakdown vs tail cost")
ax6.legend(fontsize=8)
ax6.grid(alpha=0.25, axis="y")

fig.tight_layout(rect=[0, 0, 1, 0.96])
plt.show()

3. Detailed Code Walkthrough

3.1 Parameters and the scenario set

All monetary values are in million USD. The incident loss has median $e^{\mu} = 0.5$ M$, but with $\sigma = 1.5$ its mean is $e^{\mu+\sigma^2/2} \approx 1.54$ M$ and its upper tail is very heavy. This is the typical shape of cyber losses: most incidents are small and a few are catastrophic.

The scenario set is generated once, at the top:

  • counts holds the number of incidents in each of the 40,000 simulated years.
  • year_idx repeats each year’s index once per incident, so every incident knows which year it belongs to.
  • severity holds one lognormal loss per incident.

Every candidate policy is evaluated against exactly the same 40,000 simulated years. This is the common random numbers technique. Differences between policies then reflect the policies themselves rather than sampling noise, which makes the objective surface smooth enough to optimize reliably.

3.2 The speed-up: vectorization instead of loops

A naive implementation would loop over years and incidents for every candidate $(d, L)$, roughly 48,000 incidents times 900 grid points in pure Python. The code avoids this in four ways:

  • np.clip(severity - d, 0.0, L) computes $\min{(X-d)^+, L}$ for all incidents in a single vectorized call.
  • np.bincount(year_idx, weights=..., minlength=N_YEARS) converts per-incident values into per-year totals in one pass. It replaces a Python-level group-by.
  • np.partition inside cvar finds the worst 5% of years in linear time, instead of sorting all 40,000 values.
  • The two-stage search uses a coarse 30 × 30 grid to find the global shape of the problem, then a zoom-in refinement on 15 × 15 local grids. The refinement needs only about 450 additional evaluations, and the full run takes only a few seconds.

3.3 Pricing and the objective

evaluate is the heart of the program. For an insured policy it computes the annual payout series, then applies the pricing formula: expected payout with loading $\theta$, plus a volatility charge $\gamma,\mathrm{SD}[S_{\text{pay}}]$, plus a capital charge $cL$ and a fixed fee $f$. The capital charge matters. It reflects that insurers hold capital against the limit they sell, so a higher limit costs more even when the extra layer is rarely hit. It also makes the choice of $L$ a genuine trade-off.

The retained loss is whatever the insurer does not pay, severity - payout. Adding the premium gives the total annual cost total, and from it the function returns the expected cost, the 95% VaR, the 95% CVaR and the exceedance probability $\Pr(C > W)$.

objective combines the mean and the tail as $J = (1-\rho),\mathbb{E}[C] + \rho,\mathrm{CVaR}_{0.95}(C)$. With $\rho = 0.5$, the company cares equally about its average bill and its worst-year bill.

3.4 Validation with the closed form

lev and expected_payout_analytic implement the lognormal formula from Section 1. The console report compares the simulated expected payout with the closed form for each insured strategy. A small relative gap confirms that the scenario set, the clipping logic and the bincount aggregation are all correct.

3.5 Grid search, budget and refinement

The first stage evaluates $J$, the premium and the residual tail loss on a $30 \times 30$ grid of $(d, L)$ pairs. Cells with a premium above the budget are set to infinity in J_feasible, so argmin returns the best feasible cell. A separate argmin on the raw J gives the unconstrained optimum for comparison.

The second stage zooms in around the best feasible cell twice, each time shrinking the search window by a factor of four. A candidate is accepted only if its premium respects the budget and it lowers $J$. This simple scheme is robust: it needs no gradients, handles the kinks that clipping creates in the objective, and cannot leave the feasible region.

3.6 Strategy comparison and plots

Four strategies are compared side by side: no insurance, a conventional mid-range policy ($d = 0.5$, $L = 10$), full cover ($d = 0.05$, $L = 30$) and the budget-constrained optimum. The figure uses a $2 \times 3$ layout: two 3D surfaces, one contour map, one scatter plot of the premium against residual risk, one exceedance-probability chart and one cost breakdown.

4. Console Output

====================================================================================================
Cyber insurance optimization: deductible d, limit L, premium
====================================================================================================
Scenario set: 40,000 years, 47,732 incidents
Expected annual loss without insurance : 1.843 M$
Grid evaluations: 900 in 2.84 s (total with refinement 4.26 s)
Premium budget: 1.80 M$ | Cash buffer: 8.0 M$ | CVaR level: 95% | rho = 0.50
----------------------------------------------------------------------------------------------------
Unconstrained optimum : d = 0.050, L = 30.00, premium = 3.451, J = 4.528
Budget-constrained opt: d = 1.860, L = 16.29, premium = 1.800, J = 5.947
----------------------------------------------------------------------------------------------------
Strategy               d      L  Premium  E[Ret] CVaR[Ret]  E[Cost]   VaR95  CVaR95  P(C>Buf)       J
No insurance        0.00   0.00    0.000   1.843    16.689    1.843   7.861  16.689    0.0486   9.266
Conventional        0.50  10.00    2.170   0.706     7.011    2.876   3.647   9.180    0.0129   6.028
Full cover          0.05  30.00    3.451   0.149     2.005    3.600   3.601   5.456    0.0030   4.528
Optimal (budget)    1.86  16.29    1.800   1.079     7.216    2.879   5.149   9.015    0.0081   5.947
----------------------------------------------------------------------------------------------------
Validation of the simulated expected payout against the closed-form lognormal formula
Conventional       simulated = 1.1369 M$ | analytic = 1.1407 M$ | relative gap = 0.33%
Full cover         simulated = 1.6942 M$ | analytic = 1.7018 M$ | relative gap = 0.44%
Optimal (budget)   simulated = 0.7645 M$ | analytic = 0.7691 M$ | relative gap = 0.60%
====================================================================================================

5. Result Image

6. Reading the Results

Without a budget, the optimizer buys everything

The unconstrained optimum sits in the corner of the search space: the smallest deductible and the largest limit, with a premium of about 3.45 M$. Because the objective gives half its weight to the tail, and the tail of a lognormal severity is so expensive, insuring almost everything always lowers $J$. A premium that large is nearly double the expected annual loss of 1.84 M$, which is why a real company needs a budget constraint. The cyan diamond in the top-left of panel (3) marks this unconstrained corner.

Panels (1) and (2): the 3D surfaces

Panel (1) shows $J(d, L)$ as a smooth landscape. It falls toward low deductibles and high limits, which is the direction of heavy insurance, and rises steeply toward high deductibles and low limits, where the company carries most of the tail itself. Panel (2) shows the premium surface in the opposite shape: the premium is highest at low $d$ and high $L$. The translucent cyan plane is the budget. Where the premium surface rises above the plane, the policy is unaffordable. The optimal policy sits exactly on the intersection of the two.

Panel (3): the contour map and the budget frontier

The white curve is the set of policies whose premium equals the budget. Everything to its lower-right is affordable, and everything to its upper-left is not. The red star is the best point along that curve: a deductible of about 1.86 M$ and a limit of about 16.3 M$. The curve slopes upward, which shows the trade-off the company faces. Accepting a higher deductible frees premium budget that can be spent on a larger limit. The optimizer finds the point along this curve where the next unit of budget stops buying more tail protection than it costs.

Panel (4): premium versus residual risk

Every grid point is a dot, colored by its deductible. The cloud forms a clear lower-left frontier: for a given premium, some $(d, L)$ combinations leave far less tail risk than others. Without insurance, the CVaR of retained loss is about 16.7 M$. The optimal policy brings it down to about 7.2 M$ for a premium of 1.8 M$, and it sits on the efficient frontier just left of the dashed budget line. Spending the same premium on a poorly structured policy, such as a low deductible with a small limit, would leave visibly more residual risk.

Panel (5): exceedance curves and financial impact

The vertical axis is logarithmic, so the gaps between curves are large in relative terms. The probability that the annual cost exceeds the 8 M$ cash buffer is about 4.9% with no insurance, 1.3% with the conventional policy, 0.8% with the optimal policy and 0.3% with full cover. The optimal policy therefore cuts the chance of breaching the buffer by roughly a factor of six compared with doing nothing. It is also better than the conventional policy even though it costs less. Notice the vertical drops at the left of each insured curve: they are the premium floors, the minimum cost the company pays in a year with no incident.

Panel (6): the cost breakdown

Insurance increases the expected cost, because the insurer loads the price. The expected annual cost is 1.84 M$ without insurance, but about 2.88 M$ for both the conventional and the optimal policies. What the extra cost buys is a smaller worst case: the CVaR of the total cost drops from about 16.7 M$ to about 9.0 M$ for the optimal policy, and to about 5.5 M$ for full cover. The optimal policy and the conventional policy cost the same on average, yet the optimal one has lower CVaR and a lower probability of breaching the buffer. The gain comes entirely from restructuring the policy: a higher deductible in exchange for a much larger limit.

Validation

The simulated expected payouts agree with the closed-form lognormal values to within about one percent for all three insured strategies. This confirms that the vectorized pipeline is consistent with the analytic model.

7. Conclusion

Cyber insurance is best seen as buying protection against the heavy tail, not against everyday incidents. In this example, the budget-constrained optimum accepts a deductible of about 1.9 M$ so that it can afford a limit of about 16 M$. That structure removed most of the extreme-loss exposure and cut the probability of a cash-buffer breach from about 5% to under 1%, at the same premium as a conventional policy that protected less. The framework here is easy to extend: replace the lognormal with a fitted severity distribution, add an annual aggregate limit or a coinsurance share, or price the policy with a market-quoted rate curve. The same two-stage search will still apply.