Chapter 44: Data Privacy & Compliance

1. Why Privacy Matters for System Design

Data privacy is no longer an afterthought—it fundamentally shapes system architecture. Regulations directly drive technical decisions about data storage, processing, transfer, and deletion. The stakes are existential:

Interview Callout: "Our e-commerce platform serves EU users. How would you architect data storage and processing to ensure GDPR compliance?" Answer should cover: data residency (EU region), consent management, user data deletion workflows, audit trails, DPO appointment, privacy by design principles, breach notification system.

Regulations Drive Architecture

Privacy requirements manifest as concrete technical constraints:

Regulation Requirement Architecture Impact
Data residency (GDPR, China PIPL) Region-pinned storage, geo-routing, data sovereignty
Right to be forgotten Hard delete across microservices, backup purging, cascading deletion
Breach notification (72 hours) Real-time security monitoring, incident response automation
Data portability Export APIs, standardized formats (JSON, CSV)
Consent management Consent database, purpose-based access control
Encryption requirements (HIPAA) At-rest encryption, TLS 1.3, field-level encryption

Trust as a Competitive Advantage

Privacy is not just about avoiding fines—it builds customer trust. Companies with robust privacy practices attract privacy-conscious customers, command premium pricing, and reduce churn. Transparency reports, privacy certifications (SOC 2, ISO 27001), and proactive security measures differentiate brands.

2. GDPR Key Requirements

The General Data Protection Regulation (GDPR) is the gold standard for privacy legislation. Even non-EU companies must comply if they process EU residents' data. Key obligations:

Core Principles

Key Rights

Right Description System Requirements
Right to Access Users can request copies of their data Export API, data aggregation across services, 30-day response
Right to Rectification Correct inaccurate personal data User profile edit, propagation to downstream systems
Right to Erasure (RTBF) Delete personal data upon request Cascading deletion, backup purging, 30-day completion
Right to Restrict Processing Limit data processing under certain conditions Processing suspension flags, audit trail
Right to Data Portability Receive data in structured, machine-readable format JSON/CSV export, direct transfer to other controllers
Right to Object Object to processing for direct marketing Opt-out mechanisms, marketing suppression lists

Organizational Requirements

Interview Callout: "A user requests deletion under GDPR. Walk me through your system design to fulfill this request across 15 microservices." Cover: deletion API gateway, service registry, distributed transaction/saga pattern, backup purging, audit trail, confirmation email, 30-day SLA tracking.

3. Right to Deletion (RTBF)

The Right to Be Forgotten (RTBF) is architecturally challenging. Deleting a user's data across distributed systems, backups, caches, and third-party processors requires careful orchestration.

Hard Delete vs. Soft Delete

Approach Implementation Pros Cons
Soft Delete Set deleted=true flag, filter in queries Simple rollback, preserve referential integrity, audit trail Not GDPR-compliant (data still exists), storage overhead
Hard Delete Physically remove records from database GDPR-compliant, frees storage Breaks foreign keys, complex cascades, audit challenges
Hybrid Soft delete + scheduled purge job Grace period for rollback, eventual compliance Delayed compliance, two-stage implementation

Cascading Deletion Architecture

graph TD A[User Deletion Request] --> B[API Gateway] B --> C[Deletion Orchestrator] C --> D[User Service] C --> E[Order Service] C --> F[Payment Service] C --> G[Analytics Service] C --> H[Support Ticket Service] D --> D1[Delete user profile] E --> E1[Anonymize order history] F --> F1[Delete payment methods] G --> G1[Delete analytics events] H --> H1[Redact tickets] C --> I[Backup Purge Queue] I --> J[Backup Purge Job Daily] C --> K[Audit Log] K --> L[Deletion Completed Record] C --> M[Third-party Processor API] M --> N[Marketing Platform] M --> O[CRM System]

Key Design Considerations

Interview Callout: "How do you handle RTBF for data in backups?" Answer: Backup exclusion lists (add user ID to deny list, filter during restore), short backup retention windows (30 days), never restore deleted users to production, separate legal hold mechanism.

Example Deletion Workflow

// Deletion Orchestrator pseudocode
async function deleteUser(userId) {
    const services = await serviceRegistry.getServicesWithUserData();
    const results = [];

    for (const service of services) {
        try {
            await service.deleteUser(userId);
            results.push({ service: service.name, status: 'success' });
        } catch (error) {
            results.push({ service: service.name, status: 'failed', error });
        }
    }

    // Queue backup purge
    await backupPurgeQueue.enqueue({ userId, timestamp: Date.now() });

    // Notify third-party processors
    await thirdPartyAPI.deleteUser(userId);

    // Audit log (anonymized)
    await auditLog.record({
        event: 'user_deletion',
        userId: hash(userId + SALT),
        timestamp: Date.now(),
        services: results
    });

    // Send confirmation email (before email deletion)
    await emailService.send(userId, 'Your data has been deleted');

    // Delete email last
    await emailService.deleteUser(userId);

    return results;
}

4. PII Handling

Personally Identifiable Information (PII) requires special handling. The first step is identifying what constitutes PII, then applying appropriate protection techniques.

PII Classification

Category Examples Risk Level
Direct Identifiers Name, SSN, email, phone, passport number High
Quasi-Identifiers ZIP code, birthdate, gender, job title Medium (can re-identify when combined)
Sensitive PII Health data, biometrics, financial records, race, religion Critical
Non-PII Aggregated metrics, anonymized IDs, device type Low

Protection Techniques

Tokenization

Replace sensitive data with non-sensitive tokens. Token maps to original value in secure vault.

// Tokenization example
Original: SSN = "123-45-6789"
Tokenized: SSN = "TOK_a8f3b2c1d9e4f5a6"

// Vault stores mapping
Vault: { "TOK_a8f3b2c1d9e4f5a6" => "123-45-6789" }

// Application uses token
SELECT * FROM orders WHERE customer_ssn_token = 'TOK_a8f3b2c1d9e4f5a6';

Pros: Reversible, format-preserving options, reduces PCI DSS scope. Cons: Vault becomes single point of failure, network latency for detokenization.

Pseudonymization

Replace identifying fields with pseudonyms (e.g., hashed or encrypted values). Still allows linking records for same user.

// Pseudonymization
Original: email = "alice@example.com"
Pseudonymized: email_hash = HMAC-SHA256("alice@example.com", secret_key)
              = "a1b2c3d4e5f6..."

Pros: GDPR-compliant with additional safeguards, allows analytics. Cons: Not reversible without key, vulnerable to rainbow table attacks if weak hashing.

Anonymization

Irreversibly remove identifying information. User cannot be re-identified.

PII Processing Pipeline

graph LR A[Raw Data Ingestion] --> B[PII Detection] B --> C{Classification} C -->|High Risk| D[Tokenization] C -->|Medium Risk| E[Pseudonymization] C -->|Analytics Use| F[Anonymization k-anonymity] C -->|Non-PII| G[Direct Storage] D --> H[Secure Vault] E --> I[Encrypted Storage] F --> J[Analytics Database] G --> J H --> K[Application Layer Token Exchange] I --> L[Query with Pseudonym] J --> M[Aggregate Reports]

PII Detection Automation

Manual PII tagging doesn't scale. Use automated tools:

Interview Callout: "We need to share user data with a third-party analytics vendor. How do you protect PII?" Answer: Anonymization with k-anonymity (k=5 or higher), remove direct identifiers, generalize quasi-identifiers, differential privacy for aggregates, contractual DPA with vendor, regular audits.

5. Encryption

Encryption protects data confidentiality. Three layers: at rest, in transit, and application-level.

Encryption at Rest

Protects data stored on disk from physical theft or unauthorized access.

Method Description Use Case
Full Disk Encryption Encrypts entire disk volume (BitLocker, LUKS) Laptops, physical servers, protection against theft
Database-Level Encryption Transparent Data Encryption (TDE) in databases SQL Server, Oracle, MySQL—encrypts data files
Cloud-Managed Encryption S3 SSE, EBS encryption, RDS encryption AWS/Azure/GCP managed keys, automatic encryption
Application-Level (Field) Encrypt specific columns before storing Credit cards, SSN—granular control, searchable encryption

Algorithm: AES-256

Industry standard: AES-256-GCM (Galois/Counter Mode). Provides confidentiality and authenticity. Symmetric key encryption—same key encrypts and decrypts.

Envelope Encryption

Don't encrypt all data with a single master key (key rotation nightmare). Instead, use envelope encryption:

graph TD A[Master Key in KMS] --> B[Generate Data Encryption Key DEK] B --> C[Encrypt Data with DEK] C --> D[Store Encrypted Data] A --> E[Encrypt DEK with Master Key] E --> F[Store Encrypted DEK with Data] G[Decryption Request] --> H[Retrieve Encrypted DEK] H --> I[Decrypt DEK with Master Key KMS] I --> J[Decrypt Data with DEK]

Advantages: Rotate master key without re-encrypting all data, limit blast radius (each dataset has unique DEK), offload key management to KMS.

Encryption in Transit

Protects data moving between client and server, or between services.

Application-Level Encryption (Field-Level)

Encrypt sensitive fields before writing to database. Useful when you don't trust database administrators or want defense in depth.

// Field-level encryption example (Node.js)
const crypto = require('crypto');

function encrypt(plaintext, key) {
    const iv = crypto.randomBytes(16);
    const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
    let encrypted = cipher.update(plaintext, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    const authTag = cipher.getAuthTag().toString('hex');
    return { iv: iv.toString('hex'), encrypted, authTag };
}

// Store encrypted SSN
const ssn = '123-45-6789';
const encryptedSSN = encrypt(ssn, masterKey);
db.query('INSERT INTO users (ssn_encrypted, ssn_iv, ssn_auth_tag) VALUES (?, ?, ?)',
         [encryptedSSN.encrypted, encryptedSSN.iv, encryptedSSN.authTag]);

Pros: Protects against DB admin access, SQL injection (attacker gets ciphertext), backup theft. Cons: Cannot query encrypted fields (no WHERE ssn = '123-45-6789'), key management complexity.

Searchable Encryption

Enable queries on encrypted data without decrypting. Techniques:

Interview Callout: "Explain encryption at rest, in transit, and application-level. When would you use each?" At rest: protect stored data (disk encryption, TDE). In transit: protect network traffic (TLS). Application-level: defense in depth for sensitive fields (credit cards), protection from DB admin, compliance requirements.

6. Key Management

Encryption is only as strong as key management. Poor key management negates encryption benefits.

Key Management Systems (KMS)

Solution Features Best For
AWS KMS Managed HSM, envelope encryption, CloudTrail audit, key rotation AWS-native applications, S3/RDS encryption
HashiCorp Vault Multi-cloud, dynamic secrets, leasing, key versioning Multi-cloud, hybrid environments, secret management
Google Cloud KMS Managed HSM, integration with GCP services GCP-native applications
Azure Key Vault Managed HSM, certificate management, access policies Azure-native applications, certificate lifecycle

Key Hierarchy

graph TD A[Root Key Hardware Security Module] --> B[Master Key] B --> C[Data Encryption Key 1] B --> D[Data Encryption Key 2] B --> E[Data Encryption Key N] C --> F[Encrypted Dataset 1] D --> G[Encrypted Dataset 2] E --> H[Encrypted Dataset N] A --> I[Never leaves HSM] B --> J[Rotated annually] C --> K[Rotated per dataset]

Root Key: Stored in Hardware Security Module (HSM), never leaves device. Used to encrypt master keys.

Master Key: Managed by KMS, used to encrypt Data Encryption Keys (DEKs). Rotated annually.

Data Encryption Key (DEK): Per-dataset or per-user key. Encrypted with master key. Rotated frequently (e.g., monthly).

Key Rotation

Regular key rotation limits exposure from compromised keys.

Key Storage Best Practices

Interview Callout: "How would you implement key rotation for a database with 10TB of encrypted data?" Answer: Use envelope encryption—rotate master key in KMS (cheap), re-encrypt DEKs (small overhead). For DEK rotation, use lazy rotation (re-encrypt on write) or background batch jobs. Trade-off: lazy rotation is gradual, batch is faster but resource-intensive.

7. Access Control for Data

Encryption protects data from external threats; access control protects from internal misuse.

Role-Based Access Control (RBAC) on PII

Grant access based on job role, not individual identity. Principle of least privilege.

// RBAC policy example
Roles:
  - Customer Support: Read access to name, email, order history (NOT SSN, payment info)
  - Finance Team: Read access to payment info, billing address
  - Developers: No access to production PII (use anonymized test data)
  - Auditors: Read-only access to all data + audit logs

// Enforcement in application
if (user.role === 'Customer Support') {
    return db.query('SELECT name, email, orders FROM users WHERE id = ?', [userId]);
} else if (user.role === 'Finance Team') {
    return db.query('SELECT payment_info, billing_address FROM users WHERE id = ?', [userId]);
}

Row-Level Security (RLS)

Database-enforced access control. Each user sees only authorized rows.

-- PostgreSQL Row-Level Security
CREATE POLICY customer_support_policy ON users
    USING (current_user_role() = 'Customer Support' AND consent_for_support = true);

-- Automatically filters queries
SELECT * FROM users;  -- Customer Support only sees users who consented

Pros: Enforced at DB level (can't bypass in application code), centralized policy management. Cons: Performance overhead, complex policies are hard to debug.

Column-Level Access Control

Restrict access to specific columns based on role.

-- SQL Server Column-Level Security
GRANT SELECT ON users(name, email) TO CustomerSupportRole;
DENY SELECT ON users(ssn, payment_info) TO CustomerSupportRole;

Dynamic Data Masking

Show masked data to unauthorized users.

-- SQL Server Dynamic Data Masking
ALTER TABLE users
ALTER COLUMN ssn ADD MASKED WITH (FUNCTION = 'partial(0,"XXX-XX-",4)');

-- Customer Support sees: XXX-XX-6789
-- Finance Team sees: 123-45-6789

Types of masking:

Attribute-Based Access Control (ABAC)

Access decisions based on attributes (user role, data classification, time of day, location).

// ABAC policy example
ALLOW access IF:
  user.role = "Finance" AND
  data.classification = "Financial" AND
  time_of_day BETWEEN 08:00 AND 18:00 AND
  user.location = "US"

Pros: Fine-grained, flexible, scales to complex rules. Cons: Complex to implement, requires attribute management infrastructure.

Interview Callout: "Design access control for a healthcare system where doctors can only see their patients' records." Answer: RBAC (doctor role), row-level security (patient-doctor relationship table), audit logging (who accessed what), break-glass mechanism for emergencies (with justification + alert), encryption at rest, time-limited access tokens.

8. Data Residency

Data residency requirements mandate where data is physically stored. Regulations like GDPR (EU), PIPL (China), and data localization laws (Russia, India) require user data to stay within specific borders.

Why Data Residency Matters

Cross-Border Transfer Mechanisms (GDPR)

Mechanism Description Use Case
Adequacy Decision EU Commission deems country has adequate protection Transfer to UK, Canada, Japan (as of 2025)
Standard Contractual Clauses (SCCs) EU-approved contract templates between data controller/processor Transfer to US, India, other non-adequate countries
Binding Corporate Rules (BCRs) Internal policies for multinational companies Intra-company transfers (e.g., Google, Microsoft)
User Consent Explicit, informed consent for transfer One-off transfers, limited scenarios

Multi-Region Architecture with Residency

graph TD A[Global Load Balancer GeoDNS] --> B[EU Region eu-west-1] A --> C[US Region us-east-1] A --> D[APAC Region ap-southeast-1] B --> E[EU User Data S3 + RDS EU-only] C --> F[US User Data S3 + RDS US-only] D --> G[APAC User Data S3 + RDS APAC-only] B --> H[EU Compute Services] C --> I[US Compute Services] D --> J[APAC Compute Services] H --> K[Global Shared Services Analytics, Billing] I --> K J --> K K --> L[Anonymized Data Only No PII]

Implementation Strategies

Challenges

Interview Callout: "Design a multi-region architecture for a SaaS product that must comply with GDPR data residency." Answer: GeoDNS to route EU users to EU region, region-specific databases (no cross-region replication of PII), anonymized data in central analytics, SCCs for third-party processors outside EU, audit logging per region, incident response plan per jurisdiction.

9. Audit Logging

Audit logs prove compliance, detect breaches, and support incident response. Logs must be immutable, comprehensive, and securely stored.

What to Log

Event Category Examples Retention
Access Events User login, API access, PII access, failed auth attempts 1 year (GDPR), 7 years (HIPAA)
Data Modifications Create, update, delete operations on PII 1 year minimum
Administrative Actions Role changes, permission grants, config changes 3 years (SOC 2)
Security Events Firewall blocks, intrusion attempts, malware detection 1 year
Consent Changes User grants/withdraws consent, privacy settings changes Duration of processing + 3 years

Log Entry Structure

{
  "timestamp": "2026-05-12T14:35:22Z",
  "event_type": "pii_access",
  "user_id": "user_12345",
  "user_role": "customer_support",
  "action": "read",
  "resource": "users/user_67890",
  "fields_accessed": ["name", "email", "phone"],
  "ip_address": "192.168.1.100",
  "user_agent": "Mozilla/5.0...",
  "session_id": "sess_abc123",
  "justification": "Support ticket #45678",
  "result": "success"
}

Immutable Audit Trails

Logs must be tamper-proof. If attacker gains access, they shouldn't be able to delete evidence.

Retention Requirements

Regulation Minimum Retention Notes
GDPR No specific minimum Retain only as long as necessary for purpose
HIPAA 6 years Audit logs must be retained 6 years
PCI DSS 1 year (3 months online) Audit trails for cardholder data environment
SOC 2 Varies by policy Typically 1-3 years, defined in security policy

Alerting on Suspicious Activity

Logs are useless if no one monitors them. Set up alerts for:

Interview Callout: "How do you ensure audit logs are tamper-proof?" Answer: Write-once storage (S3 Object Lock), append-only log systems, cryptographic signing (HMAC), hash chains (each entry includes hash of previous), store in separate account with restricted access, regular integrity checks.

10. Compliance Frameworks

Different regulations apply to different industries and regions. Understanding scope and requirements prevents over-engineering (and under-compliance).

Comparison Table

Framework Scope Key Requirements Penalties
GDPR EU residents' personal data Consent, RTBF, data portability, breach notification (72h), DPO Up to 4% global revenue or €20M
CCPA/CPRA California residents (revenue >$25M or 100k+ consumers) Right to know, delete, opt-out of sale, non-discrimination $2,500 per violation ($7,500 intentional)
HIPAA US healthcare providers, insurers, clearinghouses (PHI) Administrative, physical, technical safeguards; breach notification Up to $1.5M per violation category per year
SOC 2 Service providers handling customer data (voluntary) Trust Service Criteria: security, availability, confidentiality, processing integrity, privacy No legal penalty (but lose customers)
PCI DSS Entities storing/processing/transmitting credit card data Network security, access control, encryption, vulnerability mgmt, monitoring $5,000-$100,000 per month (by card brands), liability for breaches
ISO 27001 Global (voluntary certification) Information security management system (ISMS), risk assessment, controls No penalty (but certification requirement for enterprise sales)

GDPR vs. CCPA

Aspect GDPR CCPA/CPRA
Scope All personal data of EU residents Personal information of California residents
Consent Opt-in (explicit consent required) Opt-out (right to opt-out of sale)
Right to Delete Yes (with exceptions) Yes (with exceptions)
Data Portability Yes (machine-readable format) Yes (right to know/access)
Data Sale Requires consent or legal basis Right to opt-out of sale
Private Right of Action No Yes (for data breaches)

HIPAA Safeguards

HIPAA requires covered entities to implement safeguards for Protected Health Information (PHI):

PCI DSS Requirements

12 high-level requirements for cardholder data environment (CDE):

  1. Install and maintain firewall configuration
  2. Don't use vendor-supplied defaults for passwords
  3. Protect stored cardholder data (encryption)
  4. Encrypt transmission of cardholder data
  5. Use and regularly update anti-virus software
  6. Develop and maintain secure systems
  7. Restrict access to cardholder data by business need-to-know
  8. Assign unique ID to each person with computer access
  9. Restrict physical access to cardholder data
  10. Track and monitor all access to network resources
  11. Regularly test security systems and processes
  12. Maintain information security policy

Best practice: Reduce PCI DSS scope by using tokenization. Store tokens (not card numbers) in your database, delegate actual card storage to PCI-compliant payment processor (Stripe, Adyen).

Interview Callout: "Your company processes credit cards and serves EU customers. Which compliance frameworks apply?" Answer: GDPR (EU residents), PCI DSS (credit cards), possibly SOC 2 (if B2B). Architecture must support: GDPR data residency (EU region), RTBF, PCI DSS tokenization (don't store raw card numbers), encryption at rest/in transit, audit logging, breach notification procedures.

11. Privacy by Design

Privacy by Design (PbD) is a proactive approach: embed privacy into system architecture from the start, not as an afterthought.

Core Principles

  1. Proactive not reactive: Anticipate privacy risks before they materialize. Conduct Privacy Impact Assessments (PIAs) during design phase.
  2. Privacy as default: Strongest privacy settings by default. User must opt-in to data sharing, not opt-out.
  3. Privacy embedded into design: Not bolted on. Example: ephemeral messaging (Signal) where messages auto-delete.
  4. Full functionality (positive-sum): Privacy doesn't mean sacrificing features. Example: differential privacy allows analytics without compromising individual privacy.
  5. End-to-end security: Protect data throughout lifecycle (collection, storage, processing, deletion).
  6. Visibility and transparency: Clear privacy policies, user dashboards showing what data is collected.
  7. Respect for user privacy: User-centric design. Easy consent withdrawal, clear data usage explanations.

Data Minimization

Collect only data necessary for the stated purpose. Less data = less risk.

Bad Practice Good Practice
Require full name, birthdate, SSN for newsletter signup Require only email for newsletter
Store full credit card numbers Tokenize card numbers, store tokens
Collect location data for weather app (even when not in use) Collect location only when app is in use
Indefinite data retention 30-day retention for analytics, delete after

Purpose Limitation

Use data only for the purpose communicated to the user. Can't collect data for "account creation" then repurpose for "marketing" without new consent.

// Purpose tagging example
{
  "user_email": "alice@example.com",
  "consent": {
    "account_creation": true,
    "marketing": false,
    "analytics": true
  }
}

// Application logic
if (user.consent.marketing) {
    sendMarketingEmail(user.email);
} else {
    // Cannot use email for marketing
}

Storage Limitation

Retain data only as long as necessary. Implement automatic deletion policies.

// Automated deletion policy
DELETE FROM analytics_events
WHERE created_at < NOW() - INTERVAL '30 days';

DELETE FROM audit_logs
WHERE created_at < NOW() - INTERVAL '1 year';

DELETE FROM user_sessions
WHERE last_active < NOW() - INTERVAL '90 days';

Privacy Impact Assessment (PIA)

Systematic evaluation of privacy risks. Required by GDPR (Data Protection Impact Assessment) for high-risk processing.

When required: Large-scale profiling, automated decision-making with legal effects, processing of sensitive data, systematic monitoring of public areas.

PIA Steps:

  1. Describe processing: What data, why collected, how used, who has access, retention period
  2. Assess necessity: Is data collection proportionate to purpose? Can you minimize data?
  3. Identify risks: Unauthorized access, data breach, re-identification, function creep
  4. Mitigation measures: Encryption, access control, anonymization, audit logging
  5. Stakeholder consultation: Involve DPO, security team, legal, user representatives
  6. Document: Maintain PIA records for compliance audits

Privacy-Preserving Techniques

Interview Callout: "What is Privacy by Design? Give an example." Answer: Privacy by Design embeds privacy into architecture from the start. Example: Signal's ephemeral messaging (auto-delete after 7 days by default), end-to-end encryption (Signal can't read messages), minimal metadata collection (doesn't store contact lists on servers). Contrast with reactive approach: building chat app that stores all messages plaintext, then adding encryption after a breach.

Conclusion

Data privacy is not a checkbox—it's a continuous design constraint. Regulations like GDPR, CCPA, and HIPAA mandate architectural decisions around encryption, access control, data residency, and deletion. The cost of non-compliance is existential: multi-million dollar fines, customer trust erosion, and legal liability.

Key takeaways for system design interviews:

When asked about privacy in interviews, demonstrate depth: don't just say "we'll encrypt data"—explain envelope encryption, key rotation, KMS integration, and searchable encryption trade-offs. Show awareness of regulatory nuances (GDPR opt-in vs. CCPA opt-out), practical challenges (deleting data from backups), and modern privacy-preserving techniques (differential privacy, federated learning).

Privacy-conscious design builds trust, reduces risk, and increasingly drives competitive advantage. As regulations tighten globally, privacy will only grow more critical to system architecture.