Privacy by Design and Default Questions
Designing privacy into products, architectures and the software development lifecycle instead of bolting it on afterward. Covers the privacy-by-design principles and privacy-protective defaults, data minimization and purpose limitation at design time, personal-data flow mapping and PII inventory for a feature, consent and preference design including consent storage, enforcement across web and mobile and region-specific consent flows, retention and deletion design including legal holds, deletion across backups and immutable logs, provable deletion, and data-subject access, export and erasure flows, PII-safe logging, telemetry and session replay, on-device processing to limit data exposure, privacy-versus-personalization trade-offs, privacy in ML training data, feature stores and erasure from trained models, and privacy review gates, checklists, CI/CD checks, release readiness and requirements traceability inside engineering workflows. Includes designing privacy-first features, reference architectures, remediating privacy design flaws and rollout programs across product teams, and working with product, legal and security partners. Cryptographic and statistical privacy techniques, formal impact assessments, data-protection law, cross-border transfer rules, vendor risk, and encryption or access-control mechanics are covered elsewhere.
Write a function that takes a structured log event (JSON) and a set of sensitive field names and returns a copy that is safe to log. What cases make naive redaction fail?
Sample Answer
Approach. Copy the event recursively and replace sensitive values in the copy. Compare keys after normalizing them (lowercase, punctuation removed) so Api-Key and api_key match one name. Walk arrays, parse JSON hidden in strings, scrub obvious patterns (emails, and bearer tokens, the long secret strings sent in an Authorization: Bearer ... header) inside free text, and stop on cycles (an object that contains itself, directly or through a chain, which would make a naive walk loop forever and crash the logger). The original is never modified. Matching is by denylist, a list of names to hide; the alternative is an allowlist, a list of the only names permitted through, discussed below.
import json, re
REDACTED = "[REDACTED]"
EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
BEARER = re.compile(r"(?i)\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]{8,}")
def _norm(name):
return re.sub(r"[^a-z0-9]", "", name.lower())
def make_safe(event, sensitive, scrub_strings=True, _seen=None):
"""Return a deep copy of event that is safe to log. Never mutates input."""
banned = {_norm(s) for s in sensitive}
seen = _seen if _seen is not None else set()
def walk(value):
if isinstance(value, dict):
if id(value) in seen:
return "[CYCLE]"
seen.add(id(value))
out = {}
for k, v in value.items():
out[k] = REDACTED if _norm(str(k)) in banned else walk(v)
seen.discard(id(value))
return out
if isinstance(value, (list, tuple)):
if id(value) in seen:
return "[CYCLE]"
seen.add(id(value))
out = [walk(v) for v in value]
seen.discard(id(value))
return out
if isinstance(value, str):
s = value
if s[:1] in "{[":
try:
return json.dumps(walk(json.loads(s)))
except ValueError:
pass
if scrub_strings:
s = EMAIL.sub("[EMAIL]", s)
s = BEARER.sub(r"\1 " + REDACTED, s)
return s
if isinstance(value, (int, float, bool)) or value is None:
return value
return "[UNSERIALIZABLE:" + type(value).__name__ + "]"
return walk(event)
event = {
"msg": "login failed for ana@example.com",
"user": {"id": 7, "Email": "ana@example.com", "Api-Key": "k-123"},
"headers": {"Authorization": "Bearer abcdef123456", "X_Trace": "t1"},
"items": [{"password": "p1"}, {"note": "ok"}],
"payload": "{\"token\": \"t-9\", \"n\": 1}",
"blob": b"raw",
}
event["self"] = event # a cycle: the event contains itself
snapshot = repr({k: v for k, v in event.items() if k != "self"})
safe = make_safe(event, {"email", "api_key", "password", "token", "authorization"})
print(json.dumps(safe, indent=1))
print("original untouched:", repr({k: v for k, v in event.items() if k != "self"}) == snapshot)
Running it prints: msg becomes login failed for [EMAIL]; Email and Api-Key are [REDACTED]; Authorization is [REDACTED]; the password inside the list is [REDACTED]; the embedded JSON string comes out as {"token": "[REDACTED]", "n": 1}; blob becomes [UNSERIALIZABLE:bytes]; self becomes [CYCLE]; the last line is original untouched: True.
Cases where naive redaction fails
- Key variants. Exact-match on
passwordmissesPasswordandApi-Keyversusapi_key; the normalized match above fixes those, but a name likeuser_passwordstill needs a suffix or substring rule that you add and test for false positives. For example, treat a key as sensitive if its normalized form ends with a banned name:_norm("user_password")isuserpassword, which ends withpassword, so it is hidden; butpasswordhintwould not match a suffix rule, and a substring rule would also hide an innocent key such astoken_count, which is the false positive to test for. - Nesting and arrays. Top-level-only loops miss
items[0].password. - Mutation. Redacting in place destroys the caller's data or leaks through shared references.
- Hidden JSON. A body or payload logged as a string.
- PII in values (personal data, here meaning anything identifying a person, such as an email or phone number). The sensitive part is in the message text, not a field name. Regexes help but have false negatives (phone numbers, names) and false positives (a git remote such as
git@github.com:org/repo.git, wheregit@github.commatches the email pattern; and thebasicbranch of the bearer pattern above, which turns ordinary text such as "basic information" into "basic [REDACTED]", so keep that branch only if the header form needs it or require theAuthorization:prefix). - Headers and bodies. Middleware must handle header maps and request bodies, not just the top-level event.
- Cycles, huge or unserializable values. Crash the logger or the request.
- Denylist drift. A new field added next month is not on the list. For high-risk services, log only allowlisted fields.
- URLs. Tokens in query strings are not covered by the code above: parse and scrub URL query parameters too.
Complexity. Time and memory are O(n) in the size of the event. Recursion depth equals nesting depth, so cap depth for hostile input (Python's default recursion limit is about 1,000 frames).
Node.js version. The same walk applies: build new objects, normalize keys, and accept a mask function per field instead of one constant. For a card number 4111111111111111, full redaction gives [REDACTED], last-four gives ************1111, and a plain hash gives a fixed fingerprint (SHA-256 of that number starts 9bbef194...), but card numbers are a small guessable space, so anyone can hash every candidate and match it: a plain hash does not hide the value. Use a keyed hash (HMAC with a secret key held outside the logs); it still lets you check that two events refer to the same value, and without the key it cannot be enumerated.
You are redesigning a sign-up flow and want to apply data minimization without hurting conversion. Which fields, defaults and timing would you change, and how would you show that each change lowers risk?
Sample Answer
Direct answer
Collect only what the first session needs, ask for anything else at the moment a feature needs it, and make every optional or sharing setting start in its protective position. Data minimization means collecting no more personal data than a stated purpose requires.
Field-by-field redesign
| Today | Change | Why risk drops |
|---|---|---|
| Full name | Optional later, on the profile page | One less identifier stored for users who never need it |
| Keep, required (it is the login) | Needed for the account | |
| Phone | Remove; ask only if the user turns on SMS two-factor | Phone numbers are a strong identifier and a common abuse target |
| Birthdate | Replace with an "I am 16 or older" confirmation (use the age threshold counsel sets) | No date is collected at all, so only the yes/no answer is stored. If a product must verify age, a check at the edge can compute the yes/no from a date and discard the date, but the tick-box version needs no date |
| Home address | Move to checkout, only for shipped products | Collected only where a purpose exists |
| Password | Keep | Needed |
| Pre-ticked newsletter box | Unticked, separate from terms | Consent has to be a deliberate act |
Required fields at sign-up fall from 6 inputs to 2 typed inputs (email and password), plus the single "I am 16 or older" tick that replaces the birthdate. Defaults: profile private, analytics limited to what runs the service, marketing off.
Timing: progressive profiling
Ask for the extra fields the first time a feature needs them (progressive profiling: the profile fills in gradually as the user uses features), with one sentence on why. Users who never use that feature are never asked.
Showing each change lowers risk, without hurting conversion
- Data inventory diff: stored items per new account go from 6 to 3 (email, the password stored as a hash, and the yes/no age flag), listed per system (profile database, logs, analytics, email tool).
- Log check: sample sign-up logs before and after and confirm phone and birthdate no longer appear.
- Conversion: A/B test the old and new flows with a non-inferiority guardrail on sign-up completion agreed up front. Non-inferiority means the new flow only has to be no worse than the old one by more than a margin chosen in advance, because the goal is less data, not higher conversion. Illustrative: the old flow completes 62% and the margin is 1 point, so the new flow passes if the data show it is not below 61%. Showing non-inferiority within that margin, assuming the two flows truly complete at the same 62%, with 80% power and a one-sided 2.5% test, takes about 36,984 users per arm (computed in python: (1.96 + 0.8416)^2 * 2 * 0.62 * 0.38 / 0.01^2), so a small product may need to choose a wider margin or a longer run. Also track completion of the later prompts, because moving a question does not remove its cost.
- Deletion test: delete a test account and confirm fewer places need clearing.
Pitfall
Dropping a field everywhere is wrong if a real purpose needs it (a regulated product may need verified age). The test for each field is: what purpose, and could it be asked later or derived?
A team is adding social sharing and friend-finder to an existing app. How would you map the data flow end to end, including third parties, find where personal data is created and stored, and what would you hand to engineering, legal and security?
Sample Answer
Direct answer
Map by user action, not by system: for each thing a user can tap (find friends, share), list what personal data moves, where it is created and stored, and who outside the company receives it. Friend-finder is the sensitive one because it touches people who never signed up.
Flows to map
| Flow | Personal data | Created | Stored | Third party | Retention note |
|---|---|---|---|---|---|
| Contact upload for friend-finder | Names, phone numbers and emails of the user's contacts (people who are not users) | User's address book | Matching service | Possibly a matching vendor | Delete non-matches right after matching |
| Matching | Hashed identifiers against the user base | Matching service | Match results table | None | Keep results while the user keeps the feature |
| Friend graph (the stored network of who is connected to whom) | Who connected to whom | Backend | Graph store | None | Until deletion |
| Share to social | Content, link, user identifiers | App | Partner platform | Social network SDK (software development kit: a vendor's code bundled inside our app, which can collect data on its own) | Per partner contract |
| Link previews and share logs | URLs, referrer, device data | Backend | Logs, analytics | Analytics vendor | Short |
Follow one contact through it: the user uploads "Sam, +1 415 555 0123". The matching service hashes the number and compares it with the hashed numbers of registered users. If nothing matches, that row is deleted straight away. If it matches, the user is shown a suggestion for Sam, and only the match result is kept. Sam never saw a notice and never agreed to any of this, which is why the row is sensitive.
Each row carries two annotations engineering keeps in the data-flow document: a PII tag (direct identifier, contact data of a non-user, location) and a retention period.
Defaults I would set
Friend-finder and each sharing channel off until the user switches them on, with the contact upload explained before the system permission prompt appears.
What to hand over
- Engineering: the diagram with PII tags and retention annotations, plus tickets for deletion of non-matching contacts and logging redaction.
- Legal: the list of third parties and what each receives, the notice wording changes, the question of lawful basis (the legal ground that permits processing, such as consent or legitimate interests) for the contact data of non-users, contracts with vendors, and whether a DPIA (data protection impact assessment, a written risk analysis required before high-risk processing) is triggered.
- Security: the abuse paths. Hashing phone numbers does not hide them, because the number space is small enough to guess: a 10-digit number has at most 10^10 (10 billion) possibilities, so anyone holding a list of hashes can hash every possible number and look each one up. Modern hardware hashes hundreds of millions of values per second or more (ESTIMATE), so the whole space falls in well under a few minutes (10^10 divided by 3 x 10^8 per second is about 33 seconds; even at a slow 10^7 per second it is about 17 minutes; ESTIMATE). So require rate limits on matching and keep the matching service access-restricted.
Pitfall
Mapping only the first-party database misses the SDKs and partner callbacks, which is where much of the data leaves.
You are designing the privacy settings screen for a mobile app. Which controls would you expose, how would you explain the trade-offs to users in plain language, and how do you make sure what the screen says matches what the system does?
Sample Answer
Direct answer
Expose a small set of real choices, grouped by what they affect, with privacy-protective starting values. Describe each in one plain sentence about what the app does and what you give up. Then make the screen true by wiring every toggle to an enforced check in the system and testing it.
Controls to expose
- Analytics and diagnostics (on or off): off unless the user opts in where possible.
- Personalization (use my activity to tailor suggestions).
- Location (never, while using, precise or approximate), linking to the system permission.
- Marketing messages and ad personalization, separate from account emails.
- Contacts, photos and microphone access, each separate.
- Data actions: download my data, delete my account, clear history.
- Sharing and visibility of the profile.
Fewer, meaningful toggles beat thirty vague ones. Keep legal terms out of the labels.
Plain-language explanations
Say what happens either way. Example: "Personalized suggestions: we use what you watch to suggest more. If off, you still get suggestions, but they are the same for everyone." Do not use guilt wording (labels that shame the person for saying no, such as "No thanks, I don't care about my privacy") or hide the off option behind extra taps; these are called dark patterns.
Making the screen match the system
- Store each choice as one preference record (one row per user and setting, such as
user 52, analytics = off, changed 3 May), and have services read it through a single check, not copies. In code that is one shared function,is_allowed(user, "analytics"), that every service calls, instead of each service keeping its own copy of the flag. - Enforce server-side as well as in the app, since a client toggle alone can be ignored by a backend job.
- Test: an automated test turns each toggle off, then asserts that the matching events, requests or jobs stop (for example, no analytics calls fire).
- Review: privacy sign-off whenever a new data use is added, so a new use gets a toggle or a notice.
- Propagate changes to downstream systems (the other services and data pipelines that use this data) within a stated time, for example 24 hours, by publishing a change event they consume. An app that was offline keeps the old value locally, so it syncs the stored preference at next launch before sending anything, and the server rejects events from users whose record says off.
Worked example
A user switches "Analytics" off. The next app launch makes no requests to the analytics endpoint (a test confirms this), the server stops processing queued events for that user, and the screen shows when the change took effect.
You are designing telemetry for a browser used by 500 million people. It needs consent choices, sampling, low client overhead and extra care for sensitive events. How would you architect collection and processing so privacy holds at that scale?
Sample Answer
Direct answer. Enforce privacy in the client and in automation, because at 500 million people no human review can keep up. The client checks consent before anything is queued, decides sampling locally, and can only send events declared in a schema. The server strips network identifiers at the edge, splits data by sensitivity, aggregates early, and refuses to show small groups.
Data tiers
- Essential diagnostics (crash counts, version, performance): minimal, no identifiers, collected under a legal basis (the lawful reason for processing, such as consent or a legitimate need) that counsel signs off.
- Optional usage (feature use): needs the user's choice, off if they decline.
- Sensitive events (anything related to browsing, search or content): not collected by default. If a question demands it, measure on-device and send only a coarse result. For example, the browser classifies pages locally and uploads a weekly count per category such as
{news: 41, shopping: 12}, never the URLs. A per-install count is still a small browsing profile, so add noise on the device before upload (local differential privacy: each client randomly flips or perturbs its answer, so any one report is deniable but the population totals can still be recovered), and send each report under a fresh random token rather than the install ID described below, because reports sharing one install ID could be chained together for as long as that ID lasts (30 days in the example).
Client design
- Consent: the choice is stored locally and checked before an event is queued, so "no" means nothing is created, not "created and dropped on the server".
- Sampling: the client decides once per metric per period using a local random draw. At 1% that is 5 million reporting clients (500,000,000 x 0.01). At an illustrative 20 events per day, that is 100 million events per day, around 20 GB per day at 200 bytes each. Of those 5,000,000 sampled clients, a feature used by 0.1% of users still shows up on 5,000 (5,000,000 x 0.001), enough to read, which is why 1% can be enough.
- Overhead: batch events, cap queue size and daily upload bytes, upload on idle and on unmetered networks (Wi-Fi rather than a capped mobile plan), and compress.
- Identity: a random install ID, created at install, replaced by a fresh random value on a schedule (say every 30 days, illustrative) with no link kept between old and new, and deleted on opt-out, never a cross-product account ID.
Schema as the enforcement point. Every event and field is declared in a registry with data category, purpose, retention, and owner. CI fails a change that adds an undeclared field, and the ingest service rejects unknown fields. This is how privacy scales across hundreds of engineers.
Server side
- Edge (the first servers that receive uploads, before anything reaches storage): drop IP addresses before logs (keeping only coarse country) and truncate the user agent (the browser's self-description string) to browser and major version.
- Separate stores per tier with different retention (raw 30 days, aggregates longer, illustrative) and access.
- Aggregate early, publish a cell (one row of a result table, such as one country plus browser version) only if it covers a minimum number of distinct clients (say 50, illustrative). A cell with 2 clients identifies them: if you know your colleague is one of the two, the cell's "visited a health site" count tells you about them.
- Automation: automatic expiry (TTL, time-to-live), access audit and an anomaly alert on large exports.
Trade-offs. Sampling reduces rare-event visibility, so use higher rates for crashes and low-volume features and say so in the schema. Rotating IDs break long-term retention analysis, which is the price of unlinkability.
What would change my call. Strict regional rules may require region-specific consent flows and storage location, which counsel decides. A measurement need that cannot be met with coarse data should go to a privacy review before collection, not after.
Unlock Full Question Bank
Get access to all 47 Privacy by Design and Default interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.