Module contents
Lesson 30 of 39Core 115 min

Differential privacy: definition, mechanisms and proofs

Introduce differential privacy and its guarantee under auxiliary information. Develop its definition and hypothesis-testing interpretation, randomized response, sensitivity and the Laplace mechanism, postprocessing, group privacy and basic composition, with empirical checks and implementation pitfalls.

After this lesson you can

  • State (ε, δ)-DP with its adjacency relation and explain what it does and does not protect.
  • Prove randomized response and the Laplace mechanism are ε-DP and calculate their error.
  • Prove postprocessing, group privacy and basic composition.
  • Translate an (ε, δ) guarantee into a bound on membership-test TPR and FPR.
  • Empirically check the DP inequality for an implementation and detect failures such as missing clipping.

Before you start

A guarantee about changes to one individual

Anonymization can reduce direct identifiers without preventing other sources from helping infer information. Differential privacy starts with an explicit adjacency relation: for example, databases differing by the presence of one record. A randomized mechanism MM is (ε,δ)(\varepsilon,\delta)-DP if, for every ordered pair of neighboring databases D,D′D,D' and every measurable output set SS,

P[M(D)∈S]≤eεP[M(D′)∈S]+δ.\Pr[M(D)\in S]\le e^{\varepsilon}\Pr[M(D')\in S]+\delta.

The relation is usually symmetric, so the condition is also required in the other direction. The guarantee limits the effect of an individual change under that adjacency; it does not prevent inference of population statistics or automatically protect other outputs not included in the mechanism. The book by Dwork and Roth develops the definition and its mechanisms.

Before calculating ε\varepsilon, fix what counts as a unit: a record, a conversation or all contributions of one user. If a user contributes ten records and adjacency changes just one, a per-record guarantee is not automatically a per-user guarantee with the same budget. Identify the full channel too: releasing the model, validation metrics and selection decisions can reveal more than releasing only the output of a private mechanism.

The inequality does not assume the observer lacks external information: any rule combining a private output with fixed auxiliary information is postprocessing. This does not make every prior belief false or remove correlations between people; the interpretation concerns distributional change when the protected unit changes.

The size of ε\varepsilon matters in the application context: with ε=10\varepsilon=10, the multiplicative factor is e10≈22026e^{10}\approx22026, so the bound can be very wide. A “DP” label without parameters, protected unit and complete mechanism does not itself communicate how much protection is offered.

With pure privacy and two simple hypotheses about neighboring databases, Bayes offers another reading: if prior probabilities are positive, posterior odds are prior odds multiplied by a likelihood ratio bounded between e−εe^{-\varepsilon} and eεe^\varepsilon almost surely. The guarantee limits how much the output can move that comparison; it does not require posterior membership probability to be small if it was already high before observation. For δ>0\delta>0 this pointwise interpretation needs more care: δ\delta is not generally the probability that the entire guarantee “fails” for one person.

Reading it as a statistical test

The testing interpretation takes SS as outputs leading to a “member” declaration. If DD includes the person and D′D' does not, the definition gives TPR≤eεFPR+δ\mathrm{TPR}\le e^\varepsilon\mathrm{FPR}+\delta. The complementary inequality and swapping databases also restrict the possible region; this line alone is a necessary bound, not the whole region. Empirically observed rates have uncertainty and do not by themselves prove violation of a population guarantee.

For example, if δ=0\delta=0, ε=log⁡2\varepsilon=\log 2 and population FPR is 0.01, that inequality bounds TPR by 0.02. It does not say every test achieves that rate. In practice both are estimated from finite samples; a TPR lower bound and FPR upper bound can support an audit provided threshold selection and joint interval coverage are incorporated into the procedure.

If both rates and TPR>δ\mathrm{TPR}>\delta are exactly known, the same calculation gives ε≥log⁡((TPR−δ)/FPR)\varepsilon\ge\log((\mathrm{TPR}-\delta)/\mathrm{FPR}) for FPR>0\mathrm{FPR}>0 when that expression is positive. The figure applies this calculation to synthetic counts from the previous lesson as a mathematical hypothesis; it does not present those finite counts as population probabilities. If a plausible FPR interval includes larger values, the inferred bound can fall substantially. Thus a useful audit separates the set choosing the threshold from the set measuring rates.

InteractiveThe region of a binary test
The horizontal axis is FPR and the vertical axis is TPR, both from 0 to 1. The lines bound the inequalities in both directions of adjacency and their complements.
Blue marks the upper bound and orange marks the lower bound. The magenta point uses FPR 0.001 and TPR 0.051 from the earlier toy example. Its bound treats finite-sample rates as exact population rates. Establishing a real violation requires accounting for uncertainty and selection.
1.0
0.01
0.10
Minimum compatible TPR0.033
Maximum compatible TPR0.282
ε bound for this point if the rates were exact3.714
The boundaries combine inequalities in both directions and for the complementary event. The region is theoretical, not an observed ROC.

To construct the figure’s two boundaries, write t=TPRt=\mathrm{TPR}, f=FPRf=\mathrm{FPR} and a=eεa=e^\varepsilon. Applying DP to the positive event gives t≤af+δt\le af+\delta and, swapping databases, f≤at+δf\le at+\delta. Applying it to the negative event gives 1−t≤a(1−f)+δ1-t\le a(1-f)+\delta and 1−f≤a(1−t)+δ1-f\le a(1-t)+\delta. Solving for tt and combining with 0≤t≤10\le t\le1 yields

max⁡ ⁣{0,f−δa,1−a(1−f)−δ}≤t≤min⁡ ⁣{1,af+δ,1−1−f−δa}.\max\!\left\{0,\frac{f-\delta}{a},1-a(1-f)-\delta\right\} \le t\le \min\!\left\{1,af+\delta,1-\frac{1-f-\delta}{a}\right\}.

When ε=δ=0\varepsilon=\delta=0 both boundaries coincide with t=ft=f: an output identically distributed for both databases does not let that test distinguish them better than its own false-positive rate. For larger parameters the region widens. This is not a performance prediction for a specific attack; a particular mechanism may offer less information than its bound permits.

Randomized response

In randomized response, with probability qq answer with the true bit and otherwise with a fair independent bit. Final correctness probability is (1+q)/2(1+q)/2 and the maximum ratio between probabilities of an output for opposite bits is (1+q)/(1−q)(1+q)/(1-q). For q<1q<1,

ε=log⁡1+q1−q.\varepsilon=\log\frac{1+q}{1-q}.

To check this without trusting the formula, consider output “yes”. If the true bit is one, its probability is q+(1−q)/2=(1+q)/2q+(1-q)/2=(1+q)/2. If zero, only the random branch can give “yes”, with probability (1−q)/2(1-q)/2. The ratio is as stated; for output “no” the same two values are swapped. Since the output space has two elements, the bound on both outputs covers any event. If q=0q=0 the answer is independent of the bit and ε=0\varepsilon=0; if q=1q=1, an output possible for one bit has zero probability for the other and there is no finite ε\varepsilon of pure privacy.

If q=1/2q=1/2, the final answer is correct with probability 3/43/4 and ε=log⁡3\varepsilon=\log3. If q=3/4q=3/4 is the probability of choosing the truthful answer before the random branch, final accuracy is 7/87/8 and ε=log⁡7\varepsilon=\log7. These are two different parameterizations.

InteractiveRandomized survey
Expected probability of a “yes” response: 40.0 %. The deterministic simulation with seed 30 returns 396 “yes” responses out of 1000.
Unclipped estimate: 0.292. Approximate normal interval: [0.231, 0.353]. The approximation can extend beyond [0,1].
The standard error uses the hypothetical proportion and assumes i.i.d. true responses and independent randomization.
0.5
0.30
1000
Overall probability of a correct response75.0 %
Local ε1.099
Theoretical standard error0.031
Simulated estimate0.292
The simulation uses a fixed seed and synthetic data; standard error assumes i.i.d. true answers and independent randomization.

If the true fraction is pp, the probability of a “yes” answer is r=qp+(1−q)/2r=qp+(1-q)/2. For q>0q>0, (Yˉ−(1−q)/2)/q(\bar Y-(1-q)/2)/q is unbiased and, under i.i.d. responses, its variance is r(1−r)/(nq2)r(1-r)/(nq^2). The smaller qq is, the smaller ε\varepsilon is, but estimation error increases. This is local privacy: each person randomizes their answer before sending it.

Unbiasedness follows by substituting E[Yˉ]=r\mathbb E[\bar Y]=r: subtracting the expected coin contribution leaves qpqp, and dividing by qq leaves pp. For variance, a randomized response is Bernoulli with parameter rr under the population model, so Var⁡(Yˉ)=r(1−r)/n\operatorname{Var}(\bar Y)=r(1-r)/n; dividing by qq multiplies variance by 1/q21/q^2. This calculation does not require observing each person’s true answer. It does require the mechanism used to be as described and participants not to share a coin in a way that makes their answers dependent.

Central privacy sets a different trust boundary: an aggregator with access to original records calculates a result and adds noise before releasing it. The central guarantee constrains public output under defined adjacency, while the aggregator still sees input. In the local version, the aggregator receives an already randomized answer. No utility comparison is complete without stating who is trusted with input and what is released.

The estimator may fall below zero or above one in a finite sample. Clipping it to the valid interval can ease presentation but introduces bias and is another operation that must be documented. The figure shows the unclipped estimate and an approximate normal interval; near boundaries or with few answers, an appropriate binomial interval is preferable to treating that approximation as exact.

The variance above models true bits as independent draws from a population. If the bits of the nn people are considered a fixed population and only the mechanism is repeated, condition on those bits and calculate variance by summing conditional variances of their answers. The two experiments do not answer exactly the same question. In both cases, doubling nn reduces standard error by a factor near 2\sqrt2 if other parameters stay fixed, not by half.

Sensitivity and Laplace

Global sensitivity Δ1\Delta_1 is the maximum of ∥f(D)−f(D′)∥1\norm{f(D)-f(D')}_1 over neighboring databases. The Laplace mechanism adds independent noise of scale b=Δ1/εb=\Delta_1/\varepsilon to each component of a vector query. For a scalar output, the density ratio is bounded by eεe^\varepsilon thanks to the triangle inequality. For a count with add/remove adjacency, Δ1=1\Delta_1=1: if ε=0,5\varepsilon=0,5, b=2b=2, mean absolute error is 2 and standard deviation is 222\sqrt2.

In one dimension the density is proportional to e−∣y−f(D)∣/be^{-|y-f(D)|/b}. Its log ratio for DD versus D′D' is (∣y−f(D′)∣−∣y−f(D)∣)/b(|y-f(D')|-|y-f(D)|)/b, at most Δ1/b=ε\Delta_1/b=\varepsilon. The bound holds for each output and integrating it gives the bound for any event. In several dimensions exponents add and the L1L_1 norm gives the same conclusion. This proves the mechanism’s property in ideal arithmetic; a sample of values is insufficient to prove it.

In a histogram where each record belongs to one category, adding or removing a record changes one coordinate by one, so L1L_1 sensitivity is 1. Replacing one category with another can decrement one coordinate and increment another: sensitivity can be 2. The same noise code with scale 1/ε does not cover both conventions without adjusting the analysis.

Histograms also show why a contribution must be defined: if a person can appear in several categories, one person can modify more than one coordinate. Bound how many they contribute or clip their whole vector before using per-person sensitivity. Also, publishing the histogram and then its sum is postprocessing the same output; querying the database again for another sum is an additional release requiring its own accounting.

InteractiveDensities of neighboring databases
Outputs centered at 0 and 1. The horizontal window runs from −5 to 6. Blue is D and orange is D′.
The blue curve is the log density ratio. Dashed lines mark ±ε. The vertical scale runs from −1.00 to 1.00.
The displayed maximum applies only to this window. The Gaussian log ratio grows without bound. To calculate δ, approximate the normal CDF and take a weighted difference of probabilities over the region where the ratio exceeds ε.
1.0
Noise
Scale b or standard deviation σ1.00
Maximum |log ratio| in the window1.00
A sensitivity-one displacement with Laplace or Gaussian noise. The Gaussian is shown with standard deviation 1/ε to compare shapes; this choice does not automatically calibrate an (ε,δ) guarantee.

The Gaussian comparison merits a distinction. For two normal outputs with means 0 and 1 and common standard deviation σ\sigma, log ratio log⁡(p(y)/q(y))=(1−2y)/(2σ2)\log(p(y)/q(y))=(1-2y)/(2\sigma^2) is unbounded over all R\mathbb R. The event maximizing P(S)−eεQ(S)P(S)-e^\varepsilon Q(S) is that where the log ratio exceeds ε\varepsilon, namely y<a=1/2−εσ2y<a=1/2-\varepsilon\sigma^2. For this pair, the smallest additive term in that direction is

δ=Φ(a/σ)−eεΦ((a−1)/σ).\delta=\Phi(a/\sigma)-e^\varepsilon\Phi((a-1)/\sigma).

The reverse direction has the same value by symmetry. For example, σ=1\sigma=1 and ε=1\varepsilon=1 give approximately 0.1269. The figure evaluates this expression using a numerical approximation of Φ\Phi and shows a finite window; the value of δ\delta uses full tails. Balle and Wang analyze Gaussian calibration. This calculation for one pair does not replace checking global sensitivity and all neighboring pairs in an application.

For a sum of records clipped to [l,u][l,u] divided by a fixed public number NN, with absence represented by zero and 0∈[l,u]0\in[l,u], add/remove sensitivity is max⁡(∣l∣,∣u∣)/N\max(|l|,|u|)/N. Replacing one value by another gives (u−l)/N(u-l)/N. A mean with variable private denominator requires another analysis or a privatized count: do not simply reuse a fixed-size formula. Clipping is part of the mechanism and its bounds must be fixed without using private data.

Global sensitivity takes the worst case over all admissible neighboring databases, not just the largest change observed in a test sample. If before adding noise you calculate a minimum or maximum from private data and use it as a clipping bound, that step also accesses data and must be incorporated into the guarantee. Choosing public bounds too narrow reduces noise but clips values and can introduce bias; choosing them too wide increases sensitivity and error. That decision is part of the utility tradeoff, not a universal constant.

Operations on guarantees

Database-independent postprocessing applied to a private output does not worsen its parameters. Basic composition adds ε\varepsilon and δ\delta across successive releases, including adaptive ones under standard conditions. For changes of up to kk records, pure privacy gives group bound kεk\varepsilon; under approximate privacy δ\delta also grows and must be calculated. Repeating a query consumes budget even if its answers are averaged.

To see why, a randomized function of the output is represented by a kernel assigning each original output a probability of landing in a final event. Integrating the DP inequality against that kernel, which does not query the database, preserves the bound. For pure composition of two mechanisms, the joint probability ratio decomposes into the ratio for the first output and conditional ratio for the second; if the latter meets its guarantee for each first output, factors multiply and logarithms add. Arguments for δ>0\delta>0 also control exceptional masses and yield the summed basic bound.

Group privacy is obtained by chaining databases differing by one record. With (ε,δ)(\varepsilon,\delta) per record, a bound is (kε,δ∑i=0k−1eiε)(k\varepsilon,\delta\sum_{i=0}^{k-1}e^{i\varepsilon}), with the second parameter capped at 1 if necessary. This cost does not say every real group suffers exactly that loss; it is a general guarantee derived from the definition.

In an adaptive implementation, the next query can depend on previous results. Basic composition still applies when each mechanism, conditioned on every allowed history, has the declared guarantee. If history is also used to select parameters through additional access to private data, that access is part of the mechanism. Accounting must include all queries actually released, not only those appearing in the final visualization.

InteractiveComposing queries
For a fixed count with sensitivity 1, each query adds Laplace noise with scale 1/ε. The mean of k independent noise draws has standard deviation √2/(ε√k).
Composition adds up to kε for the k releases. Publishing just their mean is still post-processing of that sequence and inherits this potentially loose bound.
0.5
10
Basic composition ε5.00
Standard deviation of the mean noise0.894
The mean’s standard deviation is calculated for independent Laplace noise; the basic composition bound accounts for all releases.

The figure fixes a count’s true value and assumes independent noise in each query. Laplace noise of scale bb has variance 2b22b^2; the mean of kk independent copies has variance 2b2/k2b^2/k. This statistical improvement explains why repeating queries is a privacy decision, not merely an innocuous repetition. Bound kεk\varepsilon holds whether all answers or only a function of them are delivered; in the latter case a tighter bound may exist, but must be proved for that specific output.

Do not confuse reusing an answer with rerunning a query. If you already published a private count, plotting it and communicating the same value again postprocesses that output. If you ask the database for the count again and add fresh noise, you have run another mechanism. Likewise, setting a usage limit in an interface does not prove budget accounting: logs must cover all access paths and relevant releases.

Laboratory: checking without confusing simulation and proof

The simulation checks one randomized-response instance; the Laplace bound is checked algebraically on a grid. A finite grid or histogram never certifies the inequality for all outputs. The NumPy generator is educational and does not itself constitute a production implementation resistant to finite-precision leakage. Mironov studies how naive floating-point implementations can violate ideal-mechanism properties.

When running the cell, compare the survey estimate with 0.3 and observed absolute errors with 1/ε1/\varepsilon. They need not match exactly: each uses finitely many draws. The last line compares standard deviation of averaging twenty noise samples with 2/(ε20)\sqrt2/(\varepsilon\sqrt{20}). This error reduction does not justify forgetting the twenty accesses: joint answers have the composed budget described above.

[ ]Randomized response and Laplace boundBrowser
import numpy as np
rng = np.random.default_rng(30)
q, p, n = .5, .3, 100000
truth = rng.random(n) < p
answer = np.where(rng.random(n) < q, truth, rng.random(n) < .5)
estimate = (answer.mean()-(1-q)/2)/q
print('proporción estimada', round(estimate,4), 'real', p, 'epsilon', round(np.log((1+q)/(1-q)),4))
epsilon, sensitivity = .5, 1.
b = sensitivity/epsilon
z = np.linspace(-20,20,10001)
log_ratio = (np.abs(z-sensitivity)-np.abs(z))/b
print('máximo log-cociente en rejilla', round(log_ratio.max(),4))
assert log_ratio.max() <= epsilon+1e-12
# Histograma con un registro por categoría: sensibilidad L1 de añadir/quitar = 1.
counts = np.array([4., 3., 2.])
print('histograma ruidoso sintético', np.round(counts+rng.laplace(0,1/epsilon,3),3))
# Una suma recortada dividida por N público; ausencia representada por cero.
bounded = np.clip([.2, .8, 1.4], 0, 1); N = 10
print('media de plazas fija con ruido', round(float(bounded.sum()/N+rng.laplace(0,1/(N*epsilon))),3))
for eps in (.25, .5, 1., 2.):
    noise = rng.laplace(0,1/eps,20000)
    print('epsilon',eps,'error absoluto medio',round(float(np.abs(noise).mean()),3),
          'esperado',1/eps)
many = rng.laplace(0,1/epsilon,(10000,20)).mean(axis=1)
print('desviación al promediar 20',round(float(many.std()),3),
      'teórica',round(float(np.sqrt(2)/(epsilon*np.sqrt(20))),3))

Detecting a sensitivity failure

Suppose ε=1 is claimed for a sum divided by ten public slots and Laplace noise of scale 0.1 is added, as if all values lay in [0,1]. Without clipping, two neighboring databases can differ by value 100: their outputs are centered at 0 and 10. The event “output greater than 5” has very different probabilities. The following calculation uses analytic Laplace tails and logarithmic arithmetic; it demonstrates a counterexample to the idealized mechanism, not every possible implementation.

[ ]A counterexample without clippingBrowser
import math
b = .1
log_p_out = math.log(.5)-5/b
p_in = 1-.5*math.exp(-5/b)
log_ratio = math.log(p_in)-log_p_out
print('log cociente del evento', round(log_ratio,3), 'epsilon anunciado', 1)
assert log_ratio > 1

The proof of that failure need not recover any real record. Construct two synthetic databases allowed by the implementation and identify an output event whose ratio violates the claimed bound. The contrast between unclipped value 100 and assumed [0,1] produces a change of 10 in the mean of ten slots, one hundred times the assumed sensitivity of 0.1. If values are unbounded, global sensitivity is also unbounded. An event’s probability ratio can exceed e1e^1 even when every individual run returns a plausible number.

To correct the mechanism, clipping must happen before summation and bounds must be public or obtained by an accounted private procedure. Then calibrate noise to sensitivity of the clipped result for the declared adjacency. If changing from add/remove to replacement, or deciding to divide by the observed record count, changing a label is insufficient: rederive the maximum change of the entire query.

Exercises

Proof
Prove: Prove pure privacy of the scalar Laplace mechanism.
0
For neighbors, |f(D)−f(D′)|≤Δ and b=Δ/ε, with ε>0 and Δ>0.

Step 1 of 2. What bounds the logarithm of the density ratio?

Proof
Prove: Explain postprocessing and basic pure composition.
0
M₁ is ε₁-DP and, for every possible previous output, M₂ is ε₂-DP with respect to the same adjacency.

Step 1 of 2. Why does postprocessing the output not increase ε?

Numeric
Truth is reported with probability 3/4; otherwise a fair bit is returned. Calculate ε using natural logarithms.
Numeric
For a count with sensitivity 1 and ε=0.5, what is Laplace noise scale b?
Quiz
What does DP guarantee regarding a person?
Code
Implement private_fixed_sum_mean(x, lower, upper, N, epsilon, rng): there are N public slots, absences represented by zero and bounds containing zero. Clip, divide the sum by N and add Laplace noise with correct add/remove sensitivity. This is a mathematical exercise, not a production-ready mechanism.
def private_fixed_sum_mean(x, lower, upper, N, epsilon, rng):
  pass
Shift+Enter to run
Key idea
A DP guarantee depends on the complete mechanism, its adjacency and accounting for all outputs; simulations help explain it but do not replace a proof.