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:
- Row minimization: only records with the right consent or purpose flag are considered ($n \to n_v$).
- 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.
Speeding Up the Lattice Search
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:
- Pre-encodes every attribute at every generalization level once, as dense integer codes (
np.unique(..., return_inverse=True)). - For each node, combines the codes into a single
int64key 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 | import time |
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.kandsupp: 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_naiveis the textbook implementation: build a new DataFrame, rungroupbyon all QIs and broadcast the group size back to each row.build_codesruns 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_fastfolds the five code arrays into oneint64key with the mixed-radix formula above. Onenp.unique(..., return_counts=True)then returns all class sizes, andcnt[inv]maps each count back to its record.evaluatederives the contract metrics: records that must be suppressed, $k_{\min}$ after suppression, the mean risk $\bar{R}$ over released records, the pre-suppression riskraw_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:
- Apply the row filter (purpose limitation).
- Pre-encode the filtered data.
- 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.
- Sort the feasible nodes by $J = D + \lambda\bar{R}$ and take the best.
- 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
groupbyin 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.