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.
Design an export/data portability feature that allows users to download their data in a machine-readable format. Specify format choices, authentication and authorization checks, throttling, and how to avoid including other users' PII indirectly (e.g., comments with mentions).
Sample Answer
Direct answer. Build the export as an asynchronous job run by a dedicated export service. It re-authenticates the user, collects only data tied to that user through per-dataset exporters (one small piece of code per dataset that names the exact fields it writes, so a new table is never exported by accident, unlike a generic "select everything" query), writes JSON plus CSV files into a ZIP with a manifest (an index file listing what the ZIP contains), and delivers it through a short-lived, single-use download link. Data about other people is stripped or replaced with placeholders before anything is written.
What the law asks for. GDPR (General Data Protection Regulation) Article 20 gives people the right to receive personal data they provided, "in a structured, commonly used and machine-readable format", when processing is based on consent or contract and is automated. Article 20(4) says the right must not adversely affect the rights and freedoms of others, which is the source of the third-party PII (personally identifiable information) problem. Article 12(3) sets a response deadline of one month, extendable by two further months for complex or numerous requests. Which of your datasets count as "provided by" the user, and when repeated requests become excessive, is a call for counsel. The product can export more than the legal minimum.
Format choices
- JSON for nested data (profile, settings, posts), one file per entity type, with a
schema_versionfield and amanifest.jsonlisting files, row counts and field descriptions. An illustrative manifest:{"schema_version":"1.0","generated_at":"2026-03-13T09:30:00Z","files":[{"name":"profile.json","rows":1},{"name":"posts.json","rows":212},{"name":"orders.csv","rows":37}]}. - CSV for flat, tabular data (orders, activity history) so non-engineers can open it in a spreadsheet.
- Media in its original format. No PDF-only exports, because PDF is readable but not machine-readable.
- Stable field names and ISO 8601 timestamps (the international date format, like
2026-03-14T09:30:00Z) so another service can import it.
Authentication and authorization
- Step-up authentication (asking the user to prove who they are again, even though they are logged in, before a sensitive action): require a fresh login or second factor within the last 10 minutes (illustrative window), because an export is the highest-value payload in the account.
- The request creates a job keyed to the authenticated
subject_id. The subject comes from the session, never from a request parameter. - Each exporter has an allowlist of fields (the only fields it may write; everything else is excluded by default). A new column is excluded until someone classifies it.
- Email the account owner when a request is made and when the file is ready. Deliver via a signed link bound to the account, valid 24 hours (illustrative), single use, over HTTPS. A signed link carries an expiry time, the account ID and a signature computed with a secret only the server holds, for example
/dl/9c1e?acct=1042&exp=1773480600&sig=4cfcdc722238f1b2; changing the account or the expiry makes the signature fail, and the server also marks the link used after the first download. Encrypt the stored archive and delete it after expiry.
Throttling. Allow one active export job per user and queue the rest. Rate-limit the request endpoint per account and per IP, run workers off-peak with a size cap per part (split large exports into several ZIP parts), and limit download attempts per link. Throttling protects the system and stops an attacker with a stolen session from draining data repeatedly. It must not become a way to make the legitimate request hard, since the deadline in Article 12(3) still runs.
Keeping other users' PII out
| Item | Export treatment |
|---|---|
| The user's own posts and comments | Include the text |
| An @mention token inside the user's comment | Replace with [another user], drop the handle and ID (the comment "Thanks @dana_k, see you Friday" is exported as "Thanks [another user], see you Friday") |
| Replies written by others | Exclude, or include only a placeholder reference |
| Group chat messages from others | Exclude |
| Shared documents with co-owners | Include the user's own edits, mask co-owner names |
| Free-text that names a third party | Cannot be fully detected: keep the user's own words, since they are the author, and have counsel confirm this rule |
Enforce it with a field classification (subject, other, shared) in the exporter schema, and a test: seed two users who mention and reply to each other, run user A's export, and assert user B's ID, email and display name appear nowhere in any file.
Trade-offs. Stripping mentions makes threads less readable, so the placeholders should be consistent inside one export. Generous formats cost engineering time, so start with JSON plus CSV for the core entities.
Your product is launching in the EU, the UK, California and the rest of the world, and today one cookie banner serves everyone. How would you design a consent banner system that behaves correctly per region, and how do you make sure analytics and marketing tags really stay off until a person has agreed where that is required?
Sample Answer
Direct answer. Drive the banner from a region policy table instead of hard-coded logic: the server decides the consent mode per visitor (opt-in means nothing non-essential runs until the person agrees; opt-out means it runs until the person objects; notice-only means the person is informed), the page loads no non-essential tags until the stored consent state allows them (a tag is a small piece of third-party code, such as an analytics or advertising script, that the page loads and that sets cookies or sends data to a vendor), and automated tests plus a production scanner prove it. Counsel sets what each region requires; engineering makes the behaviour enforceable and testable.
Policy table (configuration, owned jointly by privacy and engineering)
As configuration it can be as small as a map from region to mode, for example { "EU": "opt-in", "UK": "opt-in", "US-CA": "opt-out", "default": "notice" }, plus a fallback of opt-in when the region is unknown. The page reads the mode and never contains region logic of its own.
| Region | Mode | Behaviour |
|---|---|---|
| EU and UK | Opt-in | Analytics and marketing tags stay off until the person agrees; rejecting is as easy as accepting |
| California | Opt-out | Tags may run by default, but a "Do Not Sell or Share My Personal Information" link must exist and the Global Privacy Control (GPC, a setting or extension in the person's browser that sends a "do not sell or share" signal with every request) must be honoured as an opt-out |
| Rest of world | Notice or opt-out | Notice and a preference link; stricter regions can be tightened by editing the table, not code |
The California points are the ones I would check with counsel; the California Consumer Privacy Act (CCPA) states the opt-out link, and its regulations (11 CCR 7025) require a business that sells or shares personal information to treat a qualifying opt-out preference signal such as GPC as a valid opt-out request.
Per-purpose choices. Offer separate toggles: strictly necessary (always on, no consent), analytics, marketing, personalization. A tag declares its purpose, and the tag manager (the tool that decides which tags load on a page and when) fires it only if that purpose is allowed. Vendor scripts are the third-party tags themselves.
Region detection and its failure modes. Use an edge geo-lookup (the CDN or edge server, which sits close to the visitor, maps the IP address to a country or state before the page is served). It fails with VPNs, mobile carriers, travellers and lookup errors. The rule: if the region is unknown, apply the strictest mode. Cache the banner per region (include the region in the cache key, so each region gets its own cached copy), or an EU visitor can be served a California page. Let users change region-specific choices later through a persistent preference link.
Keeping tags off until consent. Default consent state is denied. Load the tag manager with consent conditions; do not load vendor scripts at all, or set cookies, before the allowed state exists. Beware hard-coded tags, tags added by a vendor script, and server-side events that bypass the banner.
Verification
- CI: a headless browser test (an automated browser with no visible window) per region with consent denied asserts zero requests to the list of tag domains and no non-essential cookies; a second test accepts and asserts the tags fire. A sketch of the denied-consent assertion:
visit(page, region="EU", consent="denied"); assert requests_to(TAG_DOMAINS) == []; assert non_essential_cookies() == []. - Production: a scheduled crawler repeats this from each region's vantage point and alerts on new domains or cookies.
Consent record storage. Store: pseudonymous visitor or user ID, timestamp, per-purpose choice, region mode applied, banner and policy version, and source (banner, preference page, GPC signal). Withdrawal is a new record, and a policy change re-prompts. Link the record to the account when the person signs in.
You are implementing a new registration endpoint that collects: full_name, email, phone, birthdate, and profile_picture. Map the data flow and list where each PII is created, stored, transformed, cached, or logged across these components: frontend, backend API, auth service, user-profile DB, CDN, search/analytics. Provide a concise textual data-flow diagram description and identify three high-risk storage points you would prioritize for mitigation.
Sample Answer
Direct answer
Follow each field from the form to every system that touches it, noting for each whether it is created, stored, transformed, cached or logged. PII (personally identifiable information) here means all five fields. The riskiest places are usually the unintended copies, not the main database.
Data-flow description
Browser form, over TLS, to the backend API. The API sends credentials to the auth service (email plus a password hash), writes name, phone and birthdate to the user-profile database, and sends the picture to object storage that a CDN (content delivery network, edge servers that cache files near users) serves. The API then emits an event that feeds the search index and the analytics pipeline.
Per-field map
| PII | Created | Stored | Transformed | Cached | Logged |
|---|---|---|---|---|---|
| full_name | Frontend form | Profile DB, search index, analytics if sent | Lowercased and tokenised for search | Browser state | Request logs, error traces |
| Frontend form | Auth service, profile DB, email provider | Normalised; hashed for analytics joins | Session token claims | Auth and validation logs | |
| phone | Frontend form | Profile DB | Normalised to one number format | Rarely, unless API responses are cached | Validation failures with raw input |
| birthdate | Frontend form | Profile DB | Age computed; age band for analytics | Browser state | Validation failures |
| profile_picture | Camera or gallery upload | Object storage plus metadata in profile DB | Resized, thumbnails; image metadata may carry GPS | CDN edge, browser | CDN access logs (URL) |
Three high-risk storage points to fix first
- Logs and traces. Request bodies and validation errors capture email, phone and birthdate in plain text, with wide access and long retention. Mitigation: log with an allow-list of fields, redact at the logging library, and set short retention.
- Search index and analytics copies. Name and email get denormalised into stores that are hard to delete from and widely readable. Mitigation: send a pseudonymous ID instead of raw values, keep only age band, and wire deletion into the erasure flow.
- Profile pictures in object storage and CDN. Embedded location metadata, guessable URLs, and cached copies that outlive deletion. Mitigation: strip image metadata at upload, use unguessable or signed URLs, and purge the CDN on delete.
The profile database holds the most data but is the intended store, so its mitigations are access control and encryption.
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?
Unlock Full Question Bank
Get access to all 6 Privacy by Design and Default interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.