We are asked: "Develop a streaming differential privacy system for clickstream analytics: per-query budgets, hierarchical aggregation, privacy loss accounting, and user disclosures." This is a broad request. I need to design a system. Likely we need to provide a high-level architecture and maybe some code snippets? The user didn't specify language. As ChatGPT, I should produce a detailed design document. Possibly they want a conceptual design with components, and maybe pseudo-code. Could also be an implementation plan. I'll treat it as a request for a system design: architecture, modules, data flow, algorithms, privacy accounting, and user disclosures. I should cover:
-
Streaming differential privacy: handling continuous data stream, applying DP mechanisms in a streaming fashion.
-
Clickstream analytics: events like page views, clicks, etc.
-
Per-query budgets: each query (or analysis) has its own privacy budget, and we need to track usage across the system.
-
Hierarchical aggregation: multiple levels of aggregation (e.g., per user, per session, per cohort, global) and how DP is applied at each level.
-
Privacy loss accounting: tracking cumulative privacy loss (epsilon, delta) across queries and time, maybe using composition theorems (advanced composition, zero-concentrated DP, etc). Also accounting for interactions (adaptive queries).
-
User disclosures: providing users with information about how their data is used, and possibly allowing them to opt-out or control their data.
Thus, I need to produce a comprehensive design.
I should structure:
-
Introduction and requirements
-
System Overview
-
Core Components:
-
Data Ingestion: streaming click events, user identifiers (maybe anonymized), timestamps, etc.
-
Buffering and Micro-batching: for DP mechanisms, maybe use a sliding window or reservoir sampling?
-
Differential Privacy Mechanisms: for different types of queries (counts, sums, means, histograms). Use Laplace, Gaussian, or newer mechanisms (e.g., numeric mechanisms for streaming like Matrix Mechanism, or tree aggregation for time series). For streaming, need to account for repeated queries on overlapping data.
-
Privacy Budget Manager: central service to allocate and track epsilon budgets per user, per query type, per time window. Possibly using a budget accounting system (like exponential mechanism for selection? but more like a token bucket). Also need to handle hierarchical budgets: maybe budgets are allocated at different levels (e.g., per user, per cohort, per global). Could use composition to sum budgets.
-
Hierarchical Aggregation Engine: supports aggregating data at multiple granularities. For instance, first compute per-user aggregates with DP, then roll up to higher levels, possibly with additional noise. Or use a hierarchical tree structure (e.g., a stratified aggregation) to minimize noise.
-
Query Interface: API for analysts to submit queries, specifying desired privacy parameters, and the system checks budget availability and returns DP results.
-
Privacy Loss Accounting: continuously update privacy loss based on queries executed and data processed. Use composition theorems to track total epsilon. Possibly use a privacy ledger. Might also incorporate time-based decay (e.g., privacy budget recovers over time?) but DP is not typically recovered unless using local differential privacy with sliding windows.
-
User Disclosure Service: provides users with a dashboard showing what data has been collected, what analyses have been performed, how their data contributed (maybe with synthetic examples), and allows them to adjust consent, delete data, etc.
-
Monitoring and Auditing: logs for audit, detection of misuse.
-
Privacy Accounting Details:
-
Define privacy definition: (ε,δ)-DP or zCDP.
-
Mechanisms: For count queries, use Laplace noise with scale Δ/ε. For sum, etc. For streaming, need to consider composition: If we have many queries, the total privacy loss accumulates. We can use advanced composition: after k queries with each (ε_i, δ_i), total ε_total = ε_i * sqrt(2k ln(1/δ)) + k ε_i (exp(ε_i)-1) etc. Or use zCDP: composition is additive.
-
For hierarchical aggregation, we might treat each level as separate queries. Or we could design a single mechanism that releases all levels with appropriate noise (e.g., TreeAggregation for time-series, or HDMM for histograms). Might be more efficient.
-
Per-query budgets: each query consumes a portion of the user's privacy budget. Could allocate a total budget per user per day, and each query draws from that. Or allocate budgets to analyst teams.
-
Budget allocation strategies: maybe dynamic based on value of query.
-
Tracking: need to map each data point to a user, and each query's sensitivity. Since we are doing per-query budgets, we need to know which users' data contributed to each query. In a centralized setting with trusted curator, we can have a global budget; but per-query budgets may be used to limit exposure.
-
The privacy budget manager must be tamper-proof.
-
System Architecture:
-
Use a streaming platform (e.g., Apache Kafka, Flink) for ingestion.
-
A stateful processing layer that maintains per-user counts, maybe using differential privacy with a sliding window.
-
A DP query engine that can answer ad-hoc queries with precomputed DP aggregates or compute on the fly with privacy cost.
-
Storage: maybe store raw data encrypted, but for DP we often need to aggregate. Might store only aggregated DP data for retention? Or keep raw for a limited time.
-
User disclosure service: pulls data from the privacy ledger.
-
Implementation considerations:
-
Scalability: handling millions of users, high event rate.
-
Accuracy: trade-off between noise and utility; hierarchical aggregation can reduce noise by sharing across levels.
-
Flexibility: support different query types.
-
Security: protect the raw data and the DP parameters.
-
Example workflow:
-
Click event arrives, assigned a user ID (hashed for pseudonymity). Event stored in a stream.
-
The aggregation engine maintains per-user counts for various dimensions (e.g., page visits) over a sliding window (e.g., last 7 days). It could use a DP mechanism like the "online histogram" or "exponential mechanism" for each user? But that would be huge. More efficient: use a central aggregator that collects counts from each user's events and then adds noise at the cohort level. For example: we can collect all events for a time window, group by user and feature, compute counts, add Laplace noise per user, then aggregate to higher levels. However that would require storing per-user counts. Alternatively, we could use a "sample and aggregate" approach: for each query, we sample users or use a subset. But need to ensure DP.
-
Actually, typical DP system for analytics: use a trusted aggregator that collects per-user contributions (like RAPPOR, Google's DVCS). For streaming, we could have each user's data encrypted and sent to an aggregator that computes sum with Secure Aggregation? But that's not DP; that's just secure multi-party compute. DP adds noise.
-
Perhaps design: each user's client (browser or app) adds local differential privacy noise before sending data? That would be local DP, which simplifies the server trust model. But the question says "streaming differential privacy system", could be central. I'll assume central trusted curator model.
-
For central model: The server collects raw clickstreams, stores them temporarily, and answers queries with DP. The server must ensure that each query's output does not leak too much about any individual. So for each query, we compute an aggregate over the data and add noise proportional to the sensitivity (which for counting queries with a user contributing at most 1 per query is 1). However, if we have many queries, the total privacy loss across queries matters. So we need to limit the number of queries or the epsilon used per query.
-
Per-query budgets: The system can enforce that each query consumes a certain epsilon (e.g., 0.1) from a global budget. Or each analyst has a budget. Or each user has a personal budget that is not exceeded by the number of queries that involve their data? That's tricky: In central DP, the privacy guarantee is for the entire dataset; the notion of per-user budget as in local DP doesn't directly apply. However, there are concepts like "privacy allocate across users" but typically DP is about the dataset. Alternatively, we might be implementing a per-query budget as a system resource: each query can use up to a max epsilon, and the system tracks total epsilon used. That is standard.
-
The phrase "per-query budgets" might refer to the ability to assign a budget to each query (epsilon value) and enforce that the sum of epsilon used across queries does not exceed a total. That is typical. Also "hierarchical aggregation" might refer to computing aggregates at multiple granularities (e.g., per country, per city) and releasing them together with correlated noise to improve utility.
-
Privacy loss accounting: Need to track the epsilon spent per query. If we use (ε,δ)-DP, composition is more complex. Could use zCDP for easier composition: if each query is εi-zCDP, total ε_total = sum εi. Then convert to (ε,δ) for reporting. So design to use zCDP for internal accounting.
-
For each query, determine the mechanism and its zCDP parameter. For Laplace, ε_actual = 2*(sensitivity/noise_scale)^2? Actually, Laplace(Δ/ε) satisfies ε-DP but also ε^2/2-zCDP? Wait: Laplace mechanism with scale b = Δ/ε provides ε-DP. It also satisfies (ε,0)-DP. For zCDP, the relationship: For Laplace, the privacy loss random variable has variance? Actually, zCDP of Laplace is ε^2/2? Let's recall: A mechanism that is ε-DP is also (ε,0)-DP but not necessarily zCDP. However, we can convert: ε-DP implies (O(ε^2),0)-zCDP? Actually, there is a conversion: ε-DP implies (ε^2/2, ...?) I need to be precise: For a mechanism that is ε-DP, it satisfies (α/2 * ε^2, 0)-RDP for all α>1. And RDP can be converted to zCDP with factor sqrt(2). Alternatively, we can use the fact that adding Gaussian noise with scale σ satisfies (Δ/σ)^2/2 - zCDP? Actually, Gaussian mechanism: for ε<1, it satisfies (ε^2/(2σ^2))-zCDP? There's a known relation: Gaussian noise with variance σ^2 gives (Δ^2)/(2σ^2)-zCDP. So we can compute zCDP parameter as (sensitivity^2)/(2σ^2). So we can assign a zCDP parameter to each noise addition.
-
Use zCDP composition: total zCDP = sum zCDP_i. Then to report to user, convert to (ε,δ) using δ = sqrt(pi * zCDP / (2*ln(1.25?) Actually conversion: if total zCDP = ρ, then for any ε>0, δ = Φ(-ε/√(2ρ) + √(ρ/2)) + exp(ε) Φ(-ε/√(2ρ) - √(ρ/2)). But we might just use composition formulas to track total ε.
-
We need to track for each query: the set of users whose data contributed, the sensitivity, and the noise scale. The total privacy loss is per user? Actually DP composition is over the dataset; the total epsilon is the overall budget spent. So we just sum the zCDP contributions.
-
However, some queries might be on overlapping data. In streaming, if we have a sliding window and we repeatedly query the same window, the data may be reused. DP composition counts each query as a separate interaction even if the data is the same? Actually, DP composition assumes each query is an interaction that potentially reveals information. So if the same dataset is queried multiple times, each query consumes privacy budget. So we need to account.
-
Hierarchical aggregation: If we release multiple related aggregates from the same data, we can use a mechanism that releases them all at once with less total noise (like the matrix mechanism). So we might batch queries or use a precomputed DP data structure (e.g., a DP histogram for all possible groupings) to answer multiple queries with a single noise injection. That would reduce composition cost if we consider that as one "task". Need to define how to account for such a release: it's a single mechanism that answers a set of queries simultaneously. The privacy cost of that mechanism is based on the overall sensitivity of the released vector. Then subsequent queries that are linear combinations of those releases might not incur additional cost if they are derived from the same release? But if we release a DP dataset (like a synthetic dataset), then answering queries on it does not further degrade privacy of the original data (the synthetic data is already DP). However, there is a subtlety: if we release multiple synthetic datasets, composition applies. But if we release a single DP aggregate set, then analysts can query that as many times as they want without additional cost because it's already released. So the system may precompute a DP summary (like a histogram at some granularity) and allow free queries on that summary. That is common. So we need to consider that.
-
User disclosures: We need to provide users with a way to see:
-
What data about them has been collected (maybe aggregated counts).
-
Which queries have been run that may have used their data.
-
How much privacy budget has been spent on queries that include their data.
-
Option to delete their data, which would remove their contributions from future aggregates and perhaps we need to retroactively adjust? That's complex. Might just stop using future data and maybe degrade the quality of past releases? But DP doesn't allow deletion; we can't retroactively remove contribution because the output already released may have been influenced by that user's data. So we may have to note that deletion does not affect past releases. That's okay.
-
Also provide a privacy policy explaining DP and how their data is protected.
Implementation: Could have a service that, given a user ID (hashed), can retrieve the history of queries that included that user (based on logs) and the epsilon spent on those queries (maybe proportionally? Since each query's epsilon is not per user; it's for the whole dataset. But we can attribute a portion of the epsilon to each user. For a counting query, each user's contribution is at most 1, and the epsilon spent is ε_total. So we could say each user contributed ε_total/k where k is the number of users? That's not standard. Actually, the privacy budget is not allocated per user; it's a bound on how much information can be learned about any single user. So from a user's perspective, the system's total epsilon is the max information leakage about them. So we could tell the user: "The system has spent X epsilon in total, which is the maximum information that could be learned about you." That might be a disclosure.
- Alternatively, we could implement a per-user budget system: each user's data can be used up to a certain epsilon total across all queries. This would require tracking per-user epsilon consumption. That can be done: each time a query runs, we can attribute an epsilon share to each user whose data contributed. For a simple count query with sensitivity 1, the epsilon used is ε_query. We could distribute that ε equally among all users in the dataset? But the DP guarantee for each user is that the total epsilon spent across all queries that include them does not exceed some limit if we allocate it. Actually, in a trusted curator setting with group privacy, if we have n users and we run a query that uses all users, each user can be thought of as having "spent" (1/n)th of the epsilon? No. The DP guarantee is per user; the total epsilon spent on queries that involve a particular user is the sum of the ε's for those queries (since composition over datasets that differ in that one user). So if we run k queries, each with ε_i, and each query includes that user, then that user's privacy loss is sum ε_i (under pure DP composition). So to enforce a per-user budget B, we need to ensure that for each user, the sum of ε_i over all queries that include that user ≤ B. That is an additional constraint: we need to track which users are in each query (or an estimate). That might be feasible if we have a way to know the set of users that qualify for each query. For example, a query might be "count users in country X". The set of users in country X is unknown before we run the query? But we could compute it by accessing the data. Actually, to compute the query we need to know which users are in the group. So we could compute the set of user IDs that satisfy the predicate. Then we can check for each of those users whether adding this query would exceed their budget. That would require per-user budget tracking and potentially blocking queries that would exceed any user's budget. That's heavy. We could use a sampling approach to control the number of users per query, or limit the number of times a user can be included.
-
User Disclosures: We'll have a service that users can access (with their account) to see:
-
A log of times their data was used in a query (maybe aggregated: "Your data was included in 5 queries this week.").
-
The total epsilon spent on queries that involved the user (maybe the maximum epsilon that could have been learned about them). Actually, if we use (ε,δ)-DP for a query, the guarantee is that for any user, the probability ratio between neighboring datasets where that user's data differs is bounded by e^ε plus δ. So the ε is the bound on the worst-case leakage about that user. So we can report the largest ε used in any query that included the user? Or sum? Under pure composition, if multiple queries each with ε_i, the total ε for that user is sum ε_i. So we could compute total epsilon_i for all queries that included that user. We'll need to know which queries included that user. We can maintain a per-user query log: every time a query is executed, the system determines which users are in the result set (i.e., satisfy the query's WHERE clause). That could be done by scanning the user list? That might be heavy but possible if we have an index. Or we could approximate: For ad-hoc queries, we can check the condition against stored user attributes (which are hashed? but we need to know for each user whether they match). We could store a user profile (e.g., country, age group) that is used to determine inclusion. Since we need to compute aggregates, we likely have to scan through all users anyway, so we could also update a per-user "budget used" counter. But that requires iterating over all users for each query? That could be expensive. We could instead batch updates: during query execution, we compute the set of matching user IDs and for each we increment a counter. This could be done in the same aggregation job. So it's feasible.
However, if we use precomputed DP aggregates, we might not know exactly which users contributed to that release? But we can still know the set of users that were in the dataset for that release period, and since the release covers all users, all users are included. So any query that uses that release would have involved all users. So we could attribute the full epsilon of the release to all users. But that would quickly exceed per-user budgets. We might need to design releases such that they have small epsilon and are used many times. So per-user budgets could be large enough or we may not enforce per-user budgets strictly but rather report cumulative epsilon spent globally. The disclosure could just show total epsilon spent on the dataset, not per user.
The prompt says "user disclosures". It likely means we need to provide transparency to users about how their data is used. So I'll design a disclosure service that shows the user:
- What types of data are collected.
- What queries have been run (maybe aggregated by category) and when.
- The privacy budget spent on the aggregate releases that included their data.
- Option to opt out of future data collection (which would stop their data from being included in new releases; but existing releases would stand).
This is reasonable.
- Additional considerations:
-
Data minimization: Only collect necessary data.
-
Retention: Raw data deleted after a short period; only DP aggregates retained.
-
Auditing: Log all queries, budgets used, noise added, etc.
-
Access control: Only authorized analysts can run queries, with rate limiting.
-
Privacy budget replenishment: Over time, could we recover budget? In DP, we cannot "recharge" budget for the same data. But if we consider a sliding window, data older than certain age is dropped, so future queries on fresh data don't include that old data, thus effectively the privacy loss might stabilize. We could use "privacy odometer" for streaming with forgetting. That is an advanced topic. We could mention that we use a "privacy budget replenishment" based on the data retention policy: once raw data is deleted, the privacy budget associated with that data is no longer at risk because the data can't be used again. But the DP releases that used that data are already out, so they still count. But if we stop using that user's data after they opt out, then future queries won't include them, so their privacy loss stops accumulating.
-
We might also implement "user-level DP" where each user's contribution is bounded (each user can contribute at most c events per time unit). That is standard: each user's data is a vector; sensitivity is defined per user. For count queries, if each user can generate many clicks, sensitivity might be >1. So we need to bound contributions per user (e.g., clip or truncate). That is part of the design: we apply per-user contribution limits (e.g., maximum 10 clicks per day) to keep sensitivity low. We need to discuss that.
- Putting together: I'll write a description with sections:
- Introduction
- Threat model and DP definition
- System Architecture Diagram (textual)
- Components
- Data Ingestion Layer
- Stream Processing & State Management
- Privacy Budget Manager
- DP Mechanisms & Hierarchical Aggregation
- Query Engine
- Privacy Loss Accounting Module
- User Disclosure Service
- Auditing & Monitoring
- Workflow Examples
- Privacy Accounting Details
- Hierarchical Aggregation Scheme
- Scalability and Performance
- Limitations and Future Work
Since it's a design, we can include pseudo-code for key pieces, e.g., the budget allocation algorithm, or the hierarchical DP release.
I'll produce a comprehensive answer.
Streaming Differential Privacy System for Clickstream Analytics
1. Introduction
Clickstream analytics—analyzing sequences of page views, clicks, and interactions—provides valuable insights for product improvement, personalization, and business intelligence. However, clickstream data is highly personal and can reveal sensitive information about individuals. Differential Privacy (DP) offers a rigorous, mathematical guarantee that the output of an analysis does not reveal too much about any single user, even if an adversary has arbitrary side information.
We design a streaming differential privacy system that:
- Handles high‑volume click events in real time.
- Supports ad‑hoc queries with per‑query privacy budgets.
- Provides hierarchical aggregation (e.g., country → state → city) with optimized noise allocation.
- Maintains privacy loss accounting across time and queries (using zCDP/composition).
- Offers user disclosures to satisfy transparency regulations (e.g., GDPR, CCPA).
The system assumes a trusted curator model: the platform operator is trusted to handle raw data securely and to enforce DP correctly. Users’ devices may send raw clicks (or locally‑perturbed data if local DP is desired; the design can be extended).
2. Privacy Definition & Threat Model
- Guarantee: (ε, δ)-DP or zero‑concentrated DP (zCDP) for easier composition.
- Adjacency: Two datasets differing in the data of a single user (add/remove all events of that user within the analysis window). For user‑level DP we bound each user’s contribution via clipping (e.g., at most C clicks per day) so that sensitivity = C.
- Adversary: Can see all system outputs and knows the algorithm; cannot observe raw data of others.
- Re Identification: Even if an adversary knows a user’s exact data, the output distribution changes by at most e^ε (plus δ).
3. System Architecture
+-------------------+ +----------------------+ +------------------+
| Click Events | ---> | Stream Processor | ---> | Raw Data Store |
| (Kafka / HTTP) | | (Flink / Spark) | | (short‑term, |
+-------------------+ +----------------------+ | encrypted) |
+------------------+
|
v
+-------------------+ +----------------------+ +------------------+
| Analyst UI / | ---> | Query Engine | <--- | DP Aggregate |
| API Client | | (Budget Check, | | Store (hierarchical,|
+-------------------+ | Mechanism Selector) | | time‑windowed) |
+----------------------+ +------------------+
| |
v v
+----------------------+ +------------------+
| Privacy Budget | | User Disclosure |
| Manager | | Service |
+----------------------+ +------------------+
|
v
+----------------------+
| Audit & Monitoring |
+----------------------+
Key Data Flow
- Ingestion – Click events (user ID hash, timestamp, page ID, action, context) are sent to a Kafka topic.
- Stream Processor – Maintains:
- A state store with per‑user click counts (for clipping) and per‑dimension aggregates over a sliding window (e.g., last 24 h). Raw events are kept for a short period (e.g., 1 h) to support ad‑hoc queries.
- A micro‑batch scheduler that every Δt (e.g., 15 min) collects the current window’s aggregates and triggers a DP release job.
- DP Release Job – Computes hierarchical aggregates (a workload of linear queries) over the batch using a DP mechanism (e.g., HDMM). The noisy results are stored in the DP Aggregate Store with a timestamp and the privacy cost (zCDP ρ) burned.
- Query Engine – Receives analyst queries (e.g., “count clicks by country for the last 6 h”).
- Checks if the query can be answered by combining pre‑computed DP aggregates (within the stored workload). If yes, it computes the answer without additional privacy cost (since aggregates are already DP).
- If the query is not covered, it initiates an ad‑hoc DP query on the raw data (or the latest micro‑batch). The Budget Manager reserves a portion of the remaining global budget, the mechanism adds noise, and the result is returned. The privacy cost is accounted.
- Privacy Budget Manager – Maintains multiple budget pools:
- Periodic Release Pool: allocated for scheduled hierarchical releases (e.g., 10 ε per day).
- Ad‑hoc Query Pool: a separate pool for unscheduled queries (e.g., 5 ε per day). Each query request must specify a desired ε; the manager either grants it (if enough budget) or rejects/limits it.
- Per‑User Opt‑out Tracker: records which users have withdrawn consent; they are excluded from future releases/queries.
- Uses zCDP composition (additive) to track total consumption. Converts to (ε,δ) for policy reporting.
- User Disclosure Service – Authenticated users can view:
- A log of all releases/queries that included their hashed ID.
- The cumulative zCDP/ε spent on those releases (user‑level bound: sum of ε of queries they participated in, under pure composition).
- Explanation of DP and data minimization.
- Options: opt out of future collection, request data deletion (stops future inclusion; past releases remain).
- Audit & Monitoring – Immutable logs of all queries, budget assignments, noise parameters, and errors. Alerts on budget over‑use or unusual patterns.
4. Core Components Details
4.1 Data Ingestion & Pre‑Processing
- Event Format:
{user_hash, ts, page_id, action, geo, device_type, ...}
- User ID Hashing: Salted SHA‑256 to pseudonymize; raw IDs never stored long‑term.
- Clipping: Each user’s events per analysis window are limited to C (e.g., 100 clicks/day) before aggregation to guarantee sensitivity = C. Clipping is applied during stream processing: maintain a per‑user counter; once C is reached, further events are ignored for DP purposes (but may be kept for non‑DP analytics if needed, separated).
- Retention: Raw events are kept for 1 hour (configurable) in an encrypted store; then purged. Only DP aggregates are kept long‑term.
4.2 Stream Processor
- Windowing: Tumbling windows (e.g., 1 h) for periodic releases; sliding window (e.g., last 24 h) for ad‑hoc queries (reconstructed by combining recent tumbling windows).
- State:
- Per‑user click count (for clipping).
- Per‑dimension partial aggregates (e.g., counts by country, by page category). These are updated in real time and flushed at window end.
- Output: For each window, produces a pre‑DP fact table (raw counts) shaped according to the hierarchical taxonomy.
4.3 Hierarchical Taxonomy & Workload
We define a fixed set of dimensions (e.g., {geo: country > state > city, time: hour of day, page_category}) forming a lattice. The system supports queries that group by any combination of these dimensions (i.e., all possible marginals). However, releasing all 2^D marginals is infeasible; instead we choose a workload W that covers common queries:
- All one‑way marginals (counts per individual dimension value).
- Two‑way marginals for high‑cardinality × low‑cardinality pairs (e.g., country × page category).
- Top‑level totals.
The workload size |W| can be thousands but HDMM scales.
4.4 DP Mechanisms
4.4.1 Periodic Hierarchical Release (Batch)
- Use HDMM (Hierarchical Dynamic Matrix Mechanism) to answer the workload W on a given raw count vector x (length = number of leaves in the taxonomy, i.e., all combinations of dimension values).
- Construct a basis matrix B that captures the hierarchical structure (e.g., identity for leaf queries, plus structured matrices for internal nodes).
- HDMM chooses a covariance‑optimal basis that minimizes expected error under a given total privacy budget ρ (zCDP).
- The mechanism:
answer = B * (x + Lap(Δ/ε)) with correlated noise, or uses the Gaussian version for zCDP: add Gaussian noise with variance scaled by the matrix’s sensitivity.
- Sensitivity: For each leaf (user), contribution is at most C. For a query that sums over a set of leaves, sensitivity = C.
- The resulting noisy answers satisfy ρ‑zCDP where ρ = (C^2)/(2σ^2) for Gaussian, or ε for Laplace; we convert to zCDP for composition.
4.4.2 Ad‑hoc Queries
- For a query not covered by the pre‑computed aggregates, we run a one‑shot DP query on the current raw data (or on the latest micro‑batch if raw is purged).
- Mechanism: Laplace (ε‑DP) or Gaussian (ρ‑zCDP). Scale = sensitivity / ε (or sensitivity/σ for Gaussian).
- Sensitivity = C (clipped per‑user contribution).
- The query engine asks the Budget Manager for a specific ε (or ρ). The manager checks if the remaining budget can accommodate it (considering composition) and reserves it.
- The raw data is scanned; noise added; result returned.
- Composition: After each ad‑hoc query, the manager updates the global zCDP sum:
ρ_total += ρ_query. If the pool’s limit is exceeded, queries are throttled.
4.4.3 Query‑able DP Summary (Free Answers)
- Once a periodic release is stored, analysts may issue any query that is a linear combination of the released workload values. Because the release already satisfies DP, these derived queries do not consume additional privacy budget.
- The Query Engine rewrites the user’s query into a linear combination of stored noisy counts and computes the result. Error propagates but no extra leakage.
4.5 Privacy Budget Manager
- Budget Pools: Each pool has a maximum zCDP (or ε) per day (or other interval). Pools are independent; consumption does not mix.
- Tracking: For each query/release, record:
ρ (zCDP parameter)
- Set of budget pools used (e.g., ad‑hoc pool)
- Timestamp, query type
- For user‑level accounting: the list of user hashes that contributed (or an estimate via histogram).
- Composition: For a sequence of releases/queries with zCDP values ρ₁, ρ₂, …, the total ρ = Σρᵢ (by additive composition of zCDP). Convert to (ε,δ) for external reporting if needed.
- Per‑Query Allocation: The manager may enforce a max ε per query (e.g., 0.1) to avoid large one‑off drains.
- Replenishment: Pools reset periodically (e.g., daily) according to policy. Over‑use triggers alerts or query blocking.
4.6 Privacy Loss Accounting
4.7 User Disclosure Service
- Authentication: Users log in via a token linked to their hashed ID.
- Disclosures:
- Data Collection Summary: Types of clicks collected, retention period, clipping limit C.
- Query Participation Log: Each entry includes date, query description (e.g., “aggregate clicks by country”), and the ε (or ρ) of the release/query that involved the user. For a periodic release covering all users, we attribute the release’s total ε equally to each participating user? Actually, each user’s contribution to the release is bounded by the sensitivity; the release’s DP guarantee directly bounds what an attacker can learn about that user. We can simply state: “Your data contributed to a release that used ε = X on that day.” It may be clearer to say: “The total privacy budget used for analyses that included you is Y (sum of ε).”
- Cumulative Privacy Budget: Show a graph of ε spent over time (per user) and the total allowed (if we enforce a per‑user cap).
- Opt‑out / Deletion: Buttons to:
- Stop future collection: The stream processor will drop events from that user_hash.
- Delete existing data: A request to purge any retained raw data (if still within retention) and flag the user for exclusion in all subsequent releases (already processed releases remain unaffected).
- Explanation of DP: Simple language describing how noise protects their data.
The service queries the Audit Log and the Per‑User Budget Tracker (if implemented). If per‑user tracking is too heavy, we can provide an estimate (e.g., “Your data has been included in approximately N analyses”) without exact ε.
5. End‑to‑End Workflow Example
Scenario: Daily hierarchical release and an ad‑hoc query.
-
Daily Release (02:00 AM)
- The micro‑batch job collects the last 24 h of raw counts for the taxonomy (e.g., geo hierarchy).
- HDMM is invoked with total privacy budget ρ_daily = 0.5 (zCDP) → equivalent to ε≈0.5 for small δ.
- Noisy counts for all nodes are stored in DP Aggregate Store, tagged with
release_id, timestamp, ρ=0.5.
- Privacy Budget Manager deducts 0.5 from the Periodic Release Pool (daily limit 1.0).
-
Analyst Query (9:00 AM)
- Query: “Average clicks per user in California yesterday.”
- Query Engine sees that “yesterday” matches a released window. It rewrites:
avg = (sum clicks in CA) / (distinct users in CA). Both numerator and denominator are available as noisy counts from the hierarchical release (sum of leaf counts under CA; count of distinct users is also a released count in the one‑way marginal for user count). It combines them (no extra budget) and returns result.
- No privacy budget spent.
-
Analyst Ad‑hoc Query (11:00 AM)
- Query: “Count users who clicked on page X in the last 2 h.” This grouping is not in the pre‑computed workload.
- Query Engine requests ε=0.1 from the Ad‑hoc Query Pool.
- Budget Manager checks remaining ρ (e.g., remaining 0.3 zCDP → about 0.3 ε). Grants 0.1ε.
- Processor scans raw data of the last 2 h (still in raw store), applies clipping (max 1 per user? Actually sensitivity = C; but since query is distinct count, each user contributes at most 1 if we haven’t clipped; we can set C=1 for distinct count by using per‑user dedup). Mechanism: Laplace with scale = 1/ε = 10.
- The set of user hashes that match is logged for later disclosure.
- Budget Manager adds ε to the global odometer and updates per‑user cumulative ε for those users (+0.1 each).
- Result returned.
-
User Disclosure
- The user whose data contributed sees in their dashboard:
- “Your data was used in 1 ad‑hoc query on 2025‑10‑29 11:00 AM (ε=0.1).”
- “Your data contributed to the daily release on 2025‑10‑29 02:00 AM (ε=0.0005 estimated).” (If we split release ε equally among ~2000 users? Actually the release’s ε is not per‑user; but we can compute the per‑user bound as the total ε of releases that included the user. Since the release used ε=0.5 and included all users, each user’s privacy loss from that release is at most 0.5? That’s too high. Wait, (ε,δ)-DP guarantee is for the entire dataset; the definition says that for any two adjacent datasets differing in a single user, the output distributions are close. That bound is the same for every user regardless of dataset size. So a release with ε=0.5 means that an attacker can infer roughly 0.5 bits about any individual user. So if a user is in many releases, the ε they experience is the sum of ε of those releases (if the releases are all on the same underlying dataset and are sequential). Thus we can attribute the full ε of each release to each participating user. That can quickly exceed reasonable caps. However, in practice, DP practitioners often treat the global ε as the user’s privacy loss because the guarantee holds uniformly for all users. So if the system uses total ε=10 over a year, each user’s loss is ≤10. So we can just report the global ε spent on releases that included the user (i.e., the ε of those releases summed). So for a daily release with ε=0.5, the user sees +0.5 per day they are included. That may be acceptable if the budget is large enough. If we want per‑user caps, we must limit how many releases a user can be part of or use subsampling. But we can still disclose: “Your data participated in a release that used ε=0.5.” The user may question that being high; that’s a policy decision. Alternatively, we can use a mechanism where the release’s ε is much smaller (e.g., 0.01) by using more sophisticated noise allocation; then it’s fine. We’ll assume our hierarchical release uses a very small ε (e.g., 0.01) to allow many releases without exhausting per‑user budget.
6. Privacy Accounting in Depth
6.1 zCDP Composition
6.2 Accounting in the System
-
Each DP release (periodic or ad‑hoc) returns its ρ.
- For Laplacian ε‑DP: compute equivalent ρ = ε²/2.
- For Gaussian (σ, Δ): ρ = Δ²/(2σ²).
-
The Budget Manager maintains:
ρ_used_periodic = Σ ρ of all periodic releases in current pool interval
ρ_used_ad_hoc = Σ ρ of all ad‑hoc queries in current pool interval
These sums are used to check remaining budget.
-
For per‑user accounting (if implemented):
- Each ad‑hoc query that includes a user increment that user’s ε_sum by the query’s ε.
- A periodic release (if it includes all users) increments each user’s ε_sum by the release’s ε. However, this would be heavy; we could instead store a “global per‑user ε increment” that all users get when a release includes them (i.e., a flag that “you were in a release with ε=X”). Then on query, we sum across records. This can be done by storing a table
user_budget(user_hash, date, ε_inc). The number of rows equals (number of releases * number of users in release). For large user bases and many releases, this becomes huge. Instead, we can compute per‑user ε by noticing that a release that covers all users contributes the same ε to every user. So we could maintain a per‑user offset = Σ ε of all releases that included that user. Instead of writing per user per release, we can batch: For each release, we add its ε to a global “release bucket” and later compute per‑user total as that bucket’s ε if the user was present. But we need to know if the user was present. For a release covering all users, we can just add the release’s ε to every user’s total in a single operation by storing a “global release” and later when a user queries, we sum the ε of all global releases in the relevant period. That’s still O(#releases) per query but that’s manageable (like dozens). For releases that target subsets (e.g., only users in a certain region), we’d need per‑user tracking if we want accurate per‑user ε. But we could simplify: only global releases exist (the system’s hierarchical release covers all users) and ad‑hoc queries are the only ones that may target a subset. Then we can maintain a per‑user table for ad‑hoc contributions only; for global releases we just add a constant per release to the per‑user total (by summing release epsilons). That’s feasible: a user’s total ε = Σ_{ad_hoc queries they were in} ε_query + Σ_{global releases they were alive} ε_release. The latter is independent of user features; if the release includes all users in the window, then any user who had activity in that window (or just existed? Actually if they had no clicks, they might still be considered as contributing zero; they are still part of the dataset? In DP, the dataset includes all users, even those with zero counts? Typically the dataset consists of all users with their contribution vectors. If a user had no events, they are still present as a zero vector. Should they be included? To be safe, we could define that all registered users are in the dataset regardless of activity. Then every release includes all users. That simplifies: per‑user ε from global releases = Σ ε_release over the period. That’s easy to compute and disclose.
6.3 Per‑Query Budget Enforcement
- Analyst must provide an upper bound on ε (or ρ) they are willing to spend.
- Budget Manager decides whether to allow the query based on remaining budget in the requested pool and possibly on per‑user caps (if implemented). If per‑user caps, we need to estimate how many users will be included. For a query like “count distinct users with clicks on page X”, we can estimate cardinality from recent aggregates and if the resulting ε (sensitivity=1) would cause any user to exceed their cap, we might reject or subsample. To keep it simple, we skip per‑user caps for ad‑hoc; only global caps.
7. Hierarchical Aggregation in Depth
The taxonomy forms a tree (or lattice). For example, geographic dimension:
World
├─ North America
│ ├─ USA
│ │ ├─ California
│ │ │ ├─ Los Angeles
│ │ │ └─ San Francisco
│ │ └─ Texas
│ └─ Canada
└─ Europe
├─ UK
└─ Germany
We want to support counts at any node. The workload W includes all nodes’ counts.
HDMM steps:
- Encode the raw count vector x as a long vector of leaf counts (all combinations of dimensions, e.g., (geo_country, geo_city, page_category)). Size = product of cardinalities (can be large, but we can prune low‑occupancy leaves via coarsening or use a sparse representation).
- Build a set of basis matrices that transform leaf counts into the workload queries. For a tree, a natural basis is the inclusion matrix where each row corresponds to a node and has 1s for leaves under it. This matrix is huge but can be implicit.
- HDMM chooses a basis that minimizes the expected squared error under a given privacy budget. For a pure Laplace mechanism, the error covariance is proportional to B B^T where B is the basis. HDMM optimizes by re‑weighting queries and using the F盯着 algorithms.
- The mechanism: sample noise vector z ∼ Laplace(Δ/ε) in the basis domain; then compute noisy answers:
ans = B * x + z.
- In practice, for large taxonomies we use tree aggregation: add independent Laplace noise to each node with scale = (depth * Δ/ε) to preserve consistency? Actually the simple tree method: add Laplace(Δ/ε) to the root; then for each child, compute noisy count as (parent_noisy - sum of siblings’ true counts) but that uses true sibling counts, which would break DP. Better: add independent noise at each node with increasing scale to maintain consistency, but that’s wasteful. So we rely on HDMM or the Matrix Mechanism to get better utility.
We can adopt PrivTree (Feyzmaei et al.) for hierarchical data in a streaming fashion, but for the batch release we can use HDMM. The system designer pre‑defines the workload and runs HDMM offline to compute the basis; at runtime we just need to apply the matrix multiplication.
8. Stream‑Oriented Considerations
8.1 Sliding Windows vs. Disjoint Batches
- Disjoint batches (e.g., hourly) simplify privacy accounting: each batch is a separate dataset; a query over multiple batches uses the outputs of those batch releases. Since each release used its own ε, the query’s result is a linear combination of already‑noisy values; no extra DP cost if we consider that the release itself already guarantees DP for any post‑processing. However, the fact that we combine multiple releases might increase the overall ε for the underlying data because an adversary seeing multiple releases on overlapping data can infer more. Actually, if we release DP aggregates for disjoint batches, the batches are independent datasets (non‑overlapping users? may overlap if user appears in multiple hours). Overlapping user contributions across batches: each batch includes the user’s clicks in that hour; a user may appear in many batches. The DP guarantee for each batch is independent, but composition across batches applies to the user’s data across time because the datasets are adjacent? They are not neighboring because a user’s data appears in multiple batches, but the DP guarantee composition says: if we run mechanisms on datasets that may share individuals, the total privacy loss for any individual is the sum of the losses across the mechanisms (if the mechanisms are applied adaptively). This is true even if the datasets are disjoint subsets of the overall population? Actually, if the datasets are disjoint (no user appears in more than one), then composition does not add across them for a single user because the user only appears in one. But if a user can appear in multiple batches (e.g., they click in different hours), then each batch’s mechanism sees that user’s data (just a slice). Since each batch is a separate analysis, the user’s privacy budget is spent in each batch they are present. So we must compose across batches. In our design, each batch release uses a portion of the periodic budget pool. That pool’s total ε is limited, and we allocate a small ε per batch (e.g., daily total 1.0 split over 24 hourly releases → each about 0.04). Then a user who is active all day will have participated in many releases, summing to the daily pool total (≈1.0). That’s acceptable if the daily cap is the policy. So the budget pool naturally handles composition across batches.
8.2 Online / Forgetting Mechanism
Advanced option: Instead of batch releases, we could maintain a DP summary of the sliding window using a forgetting factor (e.g., exponential decay). This would allow continuous updates with a fixed amortized privacy cost. But it is complex and not required for baseline.
9. Implementation Sketch (Pseudo‑Code)
9.1 Budget Manager
class BudgetManager:
def __init__(self, periodic_limit, adhoc_limit):
self.periodic_used = 0.0 # zCDP
self.adhoc_used = 0.0
self.periodic_limit = periodic_limit
self.adhoc_limit = adhoc_limit
self.lock = threading.Lock()
def request_adhoc(self, rho_req, user_hashes=None):
with self.lock:
if self.adhoc_used + rho_req > self.adhoc_limit:
raise BudgetExceeded()
self.adhoc_used += rho_req
# Optional: update per-user
if user_hashes is not None:
for h in user_hashes:
UserBudget.increment(h, rho_req)
return True
def consume_periodic(self, rho):
with self.lock:
if self.periodic_used + rho > self.periodic_limit:
raise BudgetExceeded()
self.periodic_used += rho
def reset_daily(self):
# called at midnight
self.periodic_used = 0.0
self.adhoc_used = 0.0
# Optionally reset per-user counters daily
UserBudget.reset_daily()
class UserBudget:
# Simple example using a key-value store
@staticmethod
def increment(user_hash, rho):
# Add rho to user's cumulative zCDP (store as epsilon for simplicity)
# Could use Redis: INCRBYFLOAT user:hash:eps rho
pass
@staticmethod
def get_cumulative_epsilon(user_hash):
# return sum of (rho converted to epsilon) for that user
pass
9.2 Query Engine
class QueryEngine:
def __init__(self, dp_store, budget_mgr):
self.dp_store = dp_store
self.budget_mgr = budget_mgr
def execute(self, query):
# 1. Check if query can be answered from precomputed aggregates
if self.dp_store.can_answer(query):
result = self.dp_store.answer(query) # post-processing only
return result
# 2. Otherwise, ad-hoc DP query
# Determine privacy params (analyst may request epsilon; we pick max allowed)
eps_desired = query.desired_epsilon
rho = (eps_desired**2)/2 # if using Laplace
# Estimate number of affected users (for per-user tracking)
# Approximate using recent stats or run a quick non-DP count (with tiny budget)
est_users = self.estimate_user_count(query)
# Possibly adjust epsilon to fit per-user caps
self.budget_mgr.request_adhoc(rho, user_hashes=approx_user_set) # may be None if we don't track per-user
# Run DP mechanism on raw data (last window)
result = self._run_adhoc_dp(query, eps_desired)
# Record for disclosure
self._log_query(query, eps_desired, user_hashes=approx_user_set)
return result
9.3 HDMM Release Job (Simplified)
def run_hdmm_release(batch_counts, workload, total_rho):
# batch_counts: dict mapping (leaf_key) -> raw count (after clipping)
# workload: list of queries, each query is a subset of leaf indices
# total_rho: zCDP budget for this release
# Construct matrix B (workload queries as rows) implicitly via workload
# HDMM algorithm (from Kovalev et al.) to find basis matrices and noise scale
# For simplicity: Assume we use a precomputed basis fixed for the taxonomy.
B = build_fixed_basis(workload) # shape (|W|, |Leaves|)
# Compute covariance matrix of noise: C = (Delta^2/rho) * (B * B^T)^{-1}? Actually HDMM minimizes trace(C) etc.
# We can use the provided HDMM implementation.
noisy_answers = hdmm_mechanism(batch_counts, B, total_rho, sensitivity=CLIP_LIMIT)
# Store in dp_store
dp_store.store_release(noisy_answers, rho=total_rho, timestamp=now())
budget_mgr.consume_periodic(total_rho)
10. Scalability & Performance
- Stream Processor: Flink can handle millions of events/sec with stateful operators; per‑user state is kept in RocksDB.
- Aggregation: Hierarchical counts can be computed by grouping keys (dimensions) and aggregating counts; cardinalities are moderate (e.g., ~200 countries, ~1000 cities, ~50 categories) so leaf count size ≤ few hundred thousand – fits in memory.
- HDMM: For a workload of 10k queries and leaf size 100k, matrix operations may be heavy but can be done offline (and reused if basis fixed). Since each release recomputes on new batch counts, we need to multiply B * x quickly; B is sparse (each query selects a subset of leaves). We can implement as a sparse matrix multiply: for each query row, sum counts of its leaves then add noise. That is O(total leaves across all queries) which could be large if many queries cover many leaves. We can optimize by using the basis factorization to reduce repeated summations. Nonetheless, with modern hardware and careful code, it’s feasible.
- Ad‑hoc queries: Scans over raw data (last hour) could be expensive; we can index on dimensions to speed up filtering. The windowed raw store may be partitioned by time; querying last N hours may require scanning multiple partitions. We can maintain materialized views for common filters, but that adds storage. For low rate of ad‑hoc queries, it’s okay.
- Budget Manager: Simple transactional updates; scale is fine.
11. User Disclosure Implementation
- Backend: Provide a REST endpoint
/user/disclosure that, given an authenticated token, returns JSON:
{
"user_id": "hashed_id",
"data_collected": ["page_view", "click"],
"retention_days": 1,
"clipping_limit": 100,
"privacy_summary": {
"total_epsilon_spent": 2.34,
"daily_breakdown": [
{"date":"2025-10-29", "epsilon":0.5, "release_type":"daily"},
{"date":"2025-10-29", "epsilon":0.1, "release_type":"ad_hoc_query:12345"}
]
},
"opt_out_enabled": false,
"deletion_requested": false
}
- The endpoint queries:
releases table to sum ε where user was present (based on activity in that window, or just all global releases).
adhoc_queries table where user_hash in participants.
- The UI visualizes this data and offers opt‑out toggle (which writes to a
user_opt_out table).
12. Auditing & Monitoring
- All query submissions, budget allocations, and noise parameters are written to an immutable log (e.g., Kafka topic with compacted storage, then to HDFS).
- Regular audits recompute expected privacy loss and compare against claims.
- Anomaly detection: sudden spike in ad‑hoc queries, budget exhaustion, or repeated failures.
13. Limitations & Future Work
- Per‑User Budget Precision: Exact per‑user accounting for large releases is costly; we approximate based on release scope.
- Streaming DP: The current design uses batch releases; a fully online DP mechanism (e.g., using the matrix mechanism with forgetting) would reduce latency and noise.
- Workload Coverage: If analysts ask queries outside the predefined workload, they incur ad‑hoc cost. We could dynamically expand the workload using a budget‑aware selection algorithm.
- Local DP Option: Replace central curator with local differential privacy on the client (e.g., RAPPOR) to eliminate trust requirements; but that changes architecture.
- Non‑Linear Queries: DP for complex ML models (e.g., clustering) is out of scope but could be added as a special mechanism with its own budget pool.
14. Conclusion
The proposed system provides a practical, scalable way to derive insights from clickstream data while offering strong differential privacy guarantees. By combining periodic hierarchical releases with an ad‑hoc query path, a rigorous privacy budget manager, and transparent user disclosures, it meets both analytical needs and regulatory expectations. The modular architecture allows swapping mechanisms (Laplace, Gaussian, HDMM) and scaling components independently.