Privacy-Enhancing Technologies and Anonymization Questions
Technical safeguards that reduce identifiability: anonymization, pseudonymization, tokenization, differential privacy, and related privacy-enhancing technologies. Covers the difference between anonymized and pseudonymized data, re-identification risk, and when each technique is appropriate. Includes evaluating the privacy-utility tradeoff of a given technical control.
Technical: Provide an approach to anonymize or pseudonymize user identifiers in datasets used for exploratory dashboards without breaking cohort or retention analyses. Discuss hashing, salt management, reversible vs irreversible approaches, and how to allow authorized teams to re-identify when required for support.
Sample Answer
Requirements:
- Preserve ability to run cohort/retention analyses (stable pseudonyms across time and datasets).
- Protect PII in dashboards for general users.
- Allow authorized teams to re-identify for support with strict controls/audit.
- Scale to daily ingestion and BI queries.
High-level approach:
- Irreversible pseudonymization for general BI: compute user_id_pseudo = HMAC_SHA256(secret_key, user_id || context) stored in analytics DB. HMAC provides keyed hashing (salt via secret_key) ensuring deterministic stable mapping for cohorts but irreversible without key.
- Salt/key management: use a centrally managed KMS (AWS KMS/GCP KMS). Rotate keys periodically; maintain versioning so old data can still be resolved by retaining older key IDs. Store key metadata, not raw keys, in config service.
- Reversible path for authorized re-identification: keep minimal encrypted mapping table (user_id_pseudo → encrypted_user_id) using envelope encryption (data key encrypted with KMS). Access only via service which enforces RBAC, just-in-time decryption, MFA, and approval workflow. All requests require business justification and are logged.
- Data pipeline: producer → pii stripping service → HMAC pseudonymize → analytics store. Mapping table stored in separate vaulted DB with tighter ACLs and network isolation.
- Audit & governance: full audit trail (who, why, when), automated alerts for bulk re-identification, DSAR workflows.
- Trade-offs:
- Irreversible HMAC maximizes privacy but prevents certain support cases unless mapping stored encrypted.
- Deterministic mapping necessary for cohorts; don't use per-event random salts.
- Key rotation complexity: keep key version per record to allow historical resolution.
- Security best practices:
- Least privilege, rotate keys, split duties, encrypt at rest/in transit, anonymize sampled extracts, and include retention/deletion policies.
This design balances analytics utility (stable pseudonyms) with privacy (keyed hashing + encrypted mapping) and controlled re-identification for support.
Devise a comprehensive test plan for a privacy-preserving de-identification pipeline that will process historical user data. Include unit, integration, and regression tests, privacy and utility metrics to track (e.g., uniqueness, ARI, MAE), synthetic datasets for edge cases, and acceptance criteria required before production promotion.
Sample Answer
Overview: The test plan ensures the de-identification pipeline preserves privacy guarantees while retaining analytic utility for BI reporting. Tests span unit, integration, regression, privacy/utility monitoring, synthetic edge-case datasets, and clear acceptance criteria for production promotion.
- Unit tests (automated)
- Component-level: schema validators, PII detectors, tokenizers, hashing/salt logic, k-anonymity / l-diversity calculators.
- Assertions: deterministic behavior for fixed seed, correct handling of nulls/arrays, idempotency of transforms.
- Example: hashing with salt produces consistent pseudonym for same input and different outputs for different salts.
- Integration tests
- End-to-end pipeline on subset: ingest → de-id → transform → load into BI datastore.
- Validate schema conformity, referential integrity (keys preserved where required), timing/latency SLA.
- Run BI queries/dashboards against de-identified output and compare aggregates to originals.
- Regression tests
- Snapshot tests for sample reports/dashboards (row counts, KPIs).
- Automated checks on SQL/LookML models to detect breaking changes.
- Alert on drift of key metrics beyond thresholds.
- Privacy & utility metrics (track each run)
- Privacy: uniqueness rate (fraction of unique quasi-identifiers), k-anonymity distribution, re-identification risk estimate, differential privacy epsilon if applicable.
- Utility: Adjusted Rand Index (ARI) for clustering-preservation, MAE/MAPE for numeric aggregates, distribution distance (KS, JS divergence), histogram overlap, top-N categorical overlap.
- Monitor per-cohort and overall.
- Synthetic datasets (edge cases)
- Small populations (<k), highly skewed categories, dense quasi-identifier combinations, missing-heavy records, extreme numeric outliers, time-series with sparsity, joined datasets with referential links.
- Create adversarial set to test linkage attacks.
- Acceptance criteria before production
- Privacy: max re-identification risk <= target (e.g., <0.05) AND min k >= policy threshold for 99% of records OR epsilon <= agreed DP value.
- Utility: key BI KPIs within tolerance (e.g., MAE <2% for revenue, MAPE <5% for conversion), ARI >0.7 for defined clustering tasks, JS divergence <0.1 for primary distributions.
- Stability: no pipeline failures in 10 consecutive runs; regression tests pass; no dashboard-breaking schema changes.
- Performance: pipeline meets latency and throughput SLAs.
- Sign-off: BI owner + Privacy Officer approve metrics and runbook for incidents/rollback.
- Automation & monitoring
- CI runs unit + integration on PRs; nightly full-run with metric reports and alerting.
- Dashboard that shows privacy/utility trends, dataset lineage, and failing tests.
This plan balances regulatory privacy needs with business utility for BI reporting, provides adversarial testing, and enforces clear quantitative gates for production promotion.
You're given anonymized transaction data and asked to estimate exposure risk for a KPI that segments customers by product usage. Describe how you would quantify re-identification risk (e.g., uniqueness, small-cell frequency), what metrics you would calculate, and how you would set suppression thresholds or other controls based on dataset properties.
Sample Answer
Approach summary: assess how many KPI cells or user records are unique or small (high re‑identification risk), quantify per-cell and per-record risk, then apply suppression/generalization/noise thresholds calibrated to dataset size, sampling fraction, and business needs.
- Clarify scope & attack model
- Adversary knowledge: what external attributes might be known (age band, ZIP3, product usage)?
- Unit of attack: single user or group-level cells (KPI segments)?
- Metrics to calculate
- Cell counts and small-cell frequency: proportion of KPI segments with n = 1,2,... (report frequency distribution).
- Uniqueness rate: fraction of records that are unique on quasi-identifiers (QI set). Compute exact uniqueness and sample-uniqueness (adjust for sampling fraction).
- k-anonymity distribution: for each record, size of equivalence class on chosen QIs; report min, median, % with k<5, k<10.
- Risk score per record: 1 / k (probability of correct re-id under random guess); aggregate expected re-id risk = Σ(1/k_i)/N.
- Targeted risk: for small cells, compute cell-level re-id probability if attacker knows membership; incorporate population-to-sample correction: p_reid ≈ 1/(k * f) where f = sample/population ratio.
- Information gain: how much additional identifying power KPI adds (e.g., uniqueness before vs after adding KPI dimension).
- Setting controls & thresholds
- Fixed small-cell rule: suppress cells with count < T (common T = 5–10). Choose T based on sensitivity and legal/regulatory guidance.
- Risk-based threshold: choose acceptable aggregate expected re-id risk R_max (e.g., expected re-ids per 10k records < X). Then find minimum T such that expected risk ≤ R_max.
- Adaptive thresholds: for sparse strata (small population), increase T; for large populations, lower T. Compute required k by solving Σ_{cells with n<T} (1 / adjusted_k) ≤ R_max.
- Alternatives to suppression: generalize QIs (age bands wider), bucket low-frequency products into "Other", add calibrated noise via differential-privacy mechanisms for KPI values, or release synthetic aggregates.
- Audit & monitoring: produce a risk dashboard showing uniqueness, k-anonymity distribution, and which segments were suppressed/altered. Re-run risk assessment on each refresh.
- Example rule-of-thumb
- If population coverage is unknown or high sensitivity: T=10 and require k≥10 for all released strata.
- If population is large, trust but verify: allow T=5 for segments representing >1% population; otherwise suppress.
- Implementation notes
- Automate: SQL queries to compute equivalence class sizes, export distributions to BI tool.
- Explainability: when suppressing, show “<10” or roll-up label so stakeholders understand impact.
- Balance utility/privacy: iterate with stakeholders to choose T that minimizes analytic loss while meeting risk budget.
This quantifies risk (uniqueness, k-distribution, expected re-id) and ties controls (suppression, generalization, DP noise) to measurable thresholds driven by business sensitivity and dataset properties.
Design an analytics pipeline that applies differential privacy to product usage aggregates. Specify where to add noise (at per-query aggregation or pre-aggregated tables), how to choose and communicate an epsilon value, the privacy budget strategy for repeated queries, and metrics you would track to monitor business impact of added noise.
Sample Answer
Requirements & constraints:
- Protect user-level contributions in product-usage aggregates (DAUs, conversions, funnels) while keeping dashboards useful for product and exec decisions.
- Prefer central DP (server-side) with user-level grouping (all events from a user counted as one privacy unit).
High-level architecture:
- Event ingestion → user-level sharding & de-duplication → per-user pre-aggregation (daily/week) → DP noise injection → analytics warehouse → BI dashboards.
- Use a DP library (Google DP, OpenDP) for correct mechanisms and composition.
Where to add noise
- Prefer noise on pre-aggregated tables (per-user aggregates) before any downstream joins/rollups. Benefits: strong user-level privacy, easier budget accounting, deterministic aggregates for reproducibility.
- Mechanism: for counts/totals use Laplace (pure DP) or Gaussian (approximate DP) calibrated to sensitivity = 1 (or max contribution cap). For ratios/percentages, compute numerator and denominator with DP then post-process with confidence intervals.
- Avoid adding noise at final per-query aggregation because repeated ad-hoc queries make budget accounting harder and risk privacy leaks.
Choosing & communicating epsilon
- Map epsilon to risk/utility tradeoffs for stakeholders. Provide recommended tiers:
- Strong privacy: ε = 0.1–0.5 (high noise)
- Balanced: ε = 0.5–2.0 (practical utility)
- Lower privacy: ε = 2–8 (low noise)
- Choose default (e.g., ε = 1) after pilot experiments showing metric MAPE and decision-impact.
- Communicate in plain language on dashboards and documentation: explain privacy tier, expected noise magnitude (e.g., “counts +/- ~X at 95% CI”), and provide toggle to view noisy vs. smoothed trend estimate where allowed.
Privacy budget strategy
- Treat each user as a single privacy unit; cap contributions per reporting window (e.g., max events per user per day).
- Use periodic budget allocation: allocate ε_total per user per rolling period (e.g., ε_total = 2 per 30 days). Split across pre-aggregations (e.g., daily ε_day = ε_total/30) or assign to specific reporting endpoints.
- Use advanced composition / moments accountant to track cumulative ε across releases and analyses.
- Implement query gating and auditing: deny queries that would exceed budget, or serve cached precomputed DP aggregates instead.
- For dashboards needing many correlated metrics, use post-processing on a single noisy release where possible (compute many derived metrics from the same noisy base aggregates) to amortize budget.
Monitoring business impact
- Accuracy & stability:
- MAPE and RMSE between non-DP baseline (shadow dataset) and DP outputs.
- Signal-to-noise ratio per metric; detection power for known A/B test effects.
- Trend preservation metrics: correlation and monotonicity retention.
- Decision impact:
- Track how often decisions would flip (change in feature prioritization, alerts triggered) comparing DP vs baseline.
- Time-to-detect for anomalies under DP noise.
- Operational:
- Dashboard user complaints, number of queries rejected due to budget.
- Distribution of per-user epsilon consumption.
- Regularly run shadow analyses: run DP pipeline in parallel with internal non-DP baseline on historical data, surface expected bias/variance and produce recommended epsilon adjustments.
Practical steps for rollout
- Pilot on low-risk dashboards with different ε settings; measure MAPE, detection rates.
- Publish docs and in-dashboard note showing noise bounds and privacy tier.
- Implement budget accounting, automated audits, and fallback to cached DP aggregates.
- Iterate ε and contribution caps based on monitored business metrics and stakeholder feedback.
Trade-offs
- Pre-aggregation + central DP gives stronger guarantees and easier accounting but requires design changes early in ETL.
- Higher privacy (small ε) protects users but may reduce sensitivity for small cohorts; consider suppressing tiny cohorts and showing “insufficient data” to avoid misleading signals.
Write a SQL implementation in your chosen dialect that transforms a user table into a k-anonymous dataset for attributes [age_bucket, zipcode, gender] with k = 10. Describe your generalization strategy (e.g., bucket ranges, zipcode truncation), provide SQL steps to group and suppress rows under k, and explain limitations and testing you would perform to estimate residual re-identification risk.
Sample Answer
Approach: I use generalization for quasi-identifiers: age -> 5-year buckets, zipcode -> truncate to first 3 digits, gender -> keep but optionally coarsen to "Other/Unknown" or suppress. Then I form equivalence classes (groups) on [age_bucket, zip3, gender], count rows, and suppress (or further generalize) groups with count < 10 by marking them as suppressed (or replacing with broader values). Example uses BigQuery SQL.
Step 1 — create generalized columns
CREATE OR REPLACE TABLE project.dataset.users_generalized AS
SELECT
user_id,
-- 5-year age buckets like 20-24, 25-29
CONCAT(
CAST(FLOOR(age/5)*5 AS STRING),
'-',
CAST(FLOOR(age/5)*5 + 4 AS STRING)
) AS age_bucket,
-- first 3 digits of zipcode (assumes numeric/string)
SUBSTR(CAST(zipcode AS STRING), 1, 3) AS zip3,
-- coarsen gender, map unexpected to 'Unknown'
CASE WHEN gender IN ('M','F') THEN gender ELSE 'U' END AS gender
FROM project.dataset.users_raw;
Step 2 — compute equivalence class sizes
CREATE OR REPLACE TABLE project.dataset.eq_classes AS
SELECT
age_bucket, zip3, gender,
COUNT(*) AS cnt
FROM project.dataset.users_generalized
GROUP BY age_bucket, zip3, gender;
Step 3 — mark/suppress rows in small groups (k = 10)
Option A — suppress (set quasi-identifiers to NULL/'SUPP') for groups with cnt < 10
CREATE OR REPLACE TABLE project.dataset.users_k_anonymous AS
SELECT
u.user_id,
CASE WHEN e.cnt >= 10 THEN u.age_bucket ELSE 'SUPP' END AS age_bucket,
CASE WHEN e.cnt >= 10 THEN u.zip3 ELSE 'SUPP' END AS zip3,
CASE WHEN e.cnt >= 10 THEN u.gender ELSE 'SUPP' END AS gender
FROM project.dataset.users_generalized u
JOIN project.dataset.eq_classes e
USING(age_bucket, zip3, gender);
Option B — iterative generalization for suppressed groups
- For groups with cnt < 10, re-generalize zip3 -> zip2 (first 2 digits) or age_bucket -> 10-year buckets and recompute until cnt >= 10 or reach top-level generalization. This requires a loop in procedural SQL or a small orchestrating script.
Limitations and caveats:
- k-anonymity resists identification by those quasi-identifiers only; linkage with external datasets on other attributes can still re-identify records.
- Attribute choice matters: omitting important quasi-identifiers or keeping rare combinations leaks risk.
- Suppression reduces data utility; iterative generalization is preferable to blanket suppression.
- k-anonymity does not protect against attribute disclosure; consider l-diversity or t-closeness for sensitive attributes.
Testing and estimating residual re-identification risk:
- Compute distribution of equivalence class sizes (histogram, min, median, percentiles).
- Simulate linkage attacks: join de-identified dataset to plausible external datasets and measure unique matches per external record.
- Record re-identification rate: percentage of external records that map to a unique equivalence class.
- Use k-map risk metric: probability an equivalence class maps uniquely given population/sampling assumptions.
- Perform utility checks: key dashboard metrics before/after anonymization and measure deviation (MAE, RMSE) to balance privacy vs utility.
This pipeline can be implemented end-to-end in BigQuery with scheduled jobs; prefer iterative generalization over suppression for better analytics while monitoring equivalence-class statistics and running simulated linkage tests before release.
Unlock Full Question Bank
Get access to all 9 Privacy-Enhancing Technologies and Anonymization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.