Standards and Compliance (API Design #15)
The deal is signed — seven figures, your biggest customer yet — pending one artifact: a 200-question security and compliance questionnaire. Question 47: “Describe your process for fulfilling data subject erasure requests within statutory timeframes.” Question 83: “Where is EU customer data stored and processed?” Question 121: “Provide evidence of PCI DSS scope reduction.” Your API works beautifully. None of these questions is about whether it works.
Compliance is the set of promises your API must keep about other people’s data — promises enforced by regulators with fine schedules, not by users with feature requests. This final chapter covers the vocabulary (PII), the big regimes (GDPR, CCPA, PCI DSS, HIPAA), and — most importantly — how they flow downhill into concrete API design decisions you’ve already been making all course: minimization, retention, residency, and audit logs. It ends with a capstone and pointers onward.
By the end you will be able to read a compliance requirement and translate it into an endpoint design, a data model, and a log line.
PII: know what you carry
Everything starts with PII — personally identifiable information: data that identifies a person, directly (name, email, government id) or in combination (IP + device id + zip code is often enough). The regimes differ in details but share one logic: obligations attach to data, so the first compliance artifact is not a policy PDF — it’s a data inventory. For every field your API accepts, stores, returns, or logs: is it PII? Which regime governs it? Where does it live? How long? Who can read it?
Fields you didn’t inventory are fields you can’t protect: the email column nobody logged, the request body dumped into a debug log (Chapter 13’s warning), the analytics event with a full name. Compliance failures are usually inventory failures wearing a breach costume.
GDPR: the one that set the bar
The EU’s GDPR applies to personal data of people in the EU — wherever your company is based, if you touch their data. Its principles translate directly into API requirements:
- Lawful basis & purpose limitation — data is collected for a stated purpose and used for nothing else. Your API’s schemas become legal artifacts: asking for
phonewhen the purpose needs onlyemailis non-compliance at the JSON level. - Data minimization — collect the least, return the least. This is Chapter 2’s field selection and Chapter 9’s narrow output schemas, now with fines attached.
- The rights — access (export everything you hold on me), erasure (“right to be forgotten”: delete me), portability (give me my data in a machine-readable format), rectification. Each right is an endpoint or a job:
GET /me/export,DELETE /me— with identity verification, a deadline (30 days, one month officially), and propagation into backups, replicas, analytics, and third parties you shared with. - Breach notification — 72 hours to notify the authority after becoming aware. Chapter 13’s observability is suddenly a legal control: you cannot report what you cannot detect.
- Fines — up to 4% of global annual revenue. That’s the number that gets compliance funded.
Erasure is the one engineers underestimate: “delete from users” is easy; deleting from the warehouse, the search index, the Kafka topic retained for a year (Chapter 11), and last month’s backups is a designed system, not a SQL statement. Common pattern: crypto-shredding — encrypt per-user data with a per-user key; erasure deletes the key, rendering every copy everywhere permanently unreadable.
CCPA: the American cousin
California’s CCPA (amended by CPRA) covers California residents and is best learned against GDPR:
| GDPR | CCPA/CPRA | |
|---|---|---|
| opt model | consent before processing (opt-in) | right to opt out of sale/sharing |
| core rights | access, erasure, portability, rectification | know/access, delete, correct, opt-out of sale |
| “sale” | n/a (purpose limitation instead) | broad: sharing for value, incl. some ad analytics |
| enforcement | EU regulators, fines to 4% global revenue | per-violation fines + private right for breaches |
The API-visible deltas: a working “do not sell or share my personal information” mechanism (a preference endpoint that actually turns off downstream sharing), honoring browser Global Privacy Control signals, and the same access/delete machinery GDPR already made you build. Build for GDPR’s floor and CCPA is mostly an opt-out toggle away — which is why most teams do exactly that.
PCI DSS: the card you never touch
PCI DSS governs cardholder data — the PAN (card number), expiry, CVV. Its requirements (network segmentation, encryption, access control, logging, testing) are twelve chapters of pain, and the single most important PCI decision is scope reduction: architect so the PAN never touches your systems. Use the processor’s hosted fields or tokenization: the browser sends the card straight to Stripe/Adyen; your API receives a token (pm_1234) that charges the card without being one. Your PCI scope collapses from “your entire network” to “a questionnaire.”
If card data must touch you: never store the CVV (ever, not encrypted, not in logs), mask the PAN on display (4242 … 4242), encrypt at rest with key management, and grep your logs for 16-digit numbers in CI — the most common PCI failure is a card number in an error log.
HIPAA: health data with a chaperone
HIPAA governs PHI (protected health information) handled by covered entities (providers, insurers) and their business associates — which is you, the moment a hospital uses your API. The design-relevant rules:
- Business Associate Agreements — you sign a BAA accepting liability for PHI you handle; your subprocessors (hosting, logging SaaS!) need their own. Chapter 13’s “ship logs to a third party” requires that third party to sign a BAA first.
- Minimum necessary — every access and every API response carries the least PHI needed for the purpose. Narrow output schemas, again — the same pattern, three regimes.
- Audit controls — who accessed which patient’s data when must be recorded and reviewable. Not metrics: named, immutable audit logs of PHI access.
- No de-identification shortcut — PHI with identifiers stripped per the HIPAA method escapes the regime, but sloppy de-identification (names out, full zip + birthdate in) re-identifies people and fools no auditor. HIPAA offers two sanctioned routes: Safe Harbor (remove 18 enumerated identifier categories — names, dates finer than year, small geography, contact details, ids) and expert determination (a statistician certifies the re-identification risk is very small). For API design the practical guidance is: de-identify for analytics pipelines by dropping or coarsening fields at the pipeline boundary, not by trusting consumers to behave.
One more HIPAA-shaped API habit: separate the audit log from application logs. Access records for PHI need retention measured in years (six, commonly), immutability (append-only, tamper-evident), and their own access control — requirements your 30-day log SaaS plan does not meet. Treat the audit trail as a first-class data store with its own lifecycle, because an auditor will.
The four regimes at a glance:
| Regime | Governs | Trigger | Signature duty | Fine ceiling |
|---|---|---|---|---|
| GDPR | EU residents’ personal data | any processing, any company | consent/opt-in + the rights + 72 h breach notice | 4% global revenue |
| CCPA/CPRA | California residents | for-profit thresholds | opt-out of sale/share + access/delete | per-violation + private suits |
| PCI DSS | cardholder data | touching PAN/CVV | the twelve requirements (or scope reduction) | card-network penalties, losing processing |
| HIPAA | PHI in US healthcare | covered entity or BAA | BAAs, minimum necessary, audit controls | per-violation tiers, criminal for willful |
Non-compliance is an expected-value calculation, which is how to argue it with a finance brain:
\[ E[\text{cost}] = p_{\text{enforcement}} \times \text{fine} + p_{\text{breach}} \times \text{breach cost} + \text{deals blocked} \]
The third term is the one that bites first — like the questionnaire in this chapter’s opening, enterprise revenue increasingly requires answers before signature. Compliance is a sales feature.
Records, residency, and the paper trail
Two operational duties round out the picture. GDPR’s records of processing (Article 30) require you to document what you collect, why, where it goes, and how long it stays — for an API company, that document is the data inventory, kept alive: every new schema field triggers the question “PII? purpose? retention?” in review. And data residency — EU data processed in EU regions, some regimes stricter — is an infrastructure decision with API-shaped edges: region-pinned storage, a gateway that routes eu.api.example.com to EU services, and care that replicas, backups, and log pipelines stay in-region too. A EU database that nightly-exports to a US analytics bucket is a residency violation with good intentions.
Compliance flows downhill into design
Step back and notice the through-line: every regime’s abstract demand lands on the same handful of mechanisms, most of which this course built for other reasons:
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=4pt, minimum width=2.7cm, minimum height=0.68cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=red!14] (g) at (0,0) {GDPR / CCPA /\\PCI / HIPAA};
\node[b, fill=orange!16] (m) at (-3.9,-1.6) {minimization\\(narrow schemas)};
\node[b, fill=blue!10] (r) at (-1.3,-1.6) {retention +\\erasure jobs};
\node[b, fill=green!10] (a) at (1.3,-1.6) {access control\\(Ch. 5–7)};
\node[b, fill=gray!12] (l) at (3.9,-1.6) {audit logs\\(Ch. 13)};
\draw[a] (g) -- (m); \draw[a] (g) -- (r); \draw[a] (g) -- (a); \draw[a] (g) -- (l);
\end{tikzpicture}
Data minimization is narrow input/output schemas. Retention is TTLs and deletion jobs with proof. Residency (EU data in EU regions) is routing and storage placement decisions at the gateway and database layer. Audit logs are structured, immutable, access-scoped logs of who saw what. Breach detection is observability with a 72-hour clock. The compliant API and the well-designed API are the same API, documented twice.
The umbrella attestations: SOC 2 and ISO 27001
The questionnaire from this chapter’s opening usually isn’t asking about GDPR or PCI directly — it’s asking whether you hold SOC 2 Type II or ISO 27001. These are not laws but audited attestations that your security program exists and operates: access control, change management, incident response, vendor management, logging — the operational chapters of this course, evidenced over months. The API-design connection is real: auditors sample your actual systems, so “we rotate keys” must be a log of rotations, “we review access” must be tickets of quarterly reviews, “we test restores” must be restore reports. The lesson is the chapter’s through-line one final time: the compliant organization and the well-run one generate the same artifacts — one for the auditor, one for themselves.
Capstone: put it all together
Design the API for a telehealth startup (this is a thinking exercise — sketch it, don’t build it):
- Contract first (Ch. 2–3): model
Patient,Appointment,Note; OpenAPI spec; cursor pagination on lists. - Auth (Ch. 5–7): OIDC for clinicians; scopes (
read:notes,write:prescriptions); API keys for the EHR integration, hashed at rest, rotated quarterly. - Security (Ch. 9): object-level checks on every
/patients/{id}access; narrowPatientViewschema; rate limits. - Real-time (Ch. 4): SSE for appointment updates; signed webhooks to the billing system.
- Performance & scale (Ch. 10–11): p95 budget per endpoint; async document generation via queue; circuit breaker on the insurance-eligibility provider.
- Quality (Ch. 12–13): contract tests against the EHR sandbox; RED dashboards; PHI-free structured logs with correlation ids; SLO 99.9%.
- Lifecycle (Ch. 14):
/v1with additive-only policy; idempotency keys on payments; problem+json errors. - Compliance (this chapter): HIPAA + BAA inventory of every subprocessor; minimum-necessary review of every schema field; immutable access audit log; erasure-by-crypto-shredding for patient data.
Eight steps, fifteen chapters, one API you’d actually trust.
Where next
This course followed roadmap.sh/api-design; the natural continuations are the Backend roadmap (databases, caching, scaling beneath the API), DevOps (deploying and operating it), and GraphQL (going deeper on Chapter 2’s query-language style). The through-line of all fifteen chapters fits in one sentence: an API is a promise — about shape, behavior, safety, and time — and good API design is the engineering of promises you can keep.
Pitfalls
- Compliance as a launch-week activity. Erasure propagation and residency are architecture; retrofitting them costs ten times the design-time price. Inventory PII on day one.
- Collecting “just in case.” Every unneeded PII field is unneeded liability under three regimes. Minimization is the cheapest control that exists.
- PII in logs and analytics. The most common real-world leak: request bodies, emails, and tokens in log pipelines shipped to third parties. Redact at emission; audit the pipeline.
- Storing card data to “simplify.” Keeping PANs to save a redirect buys a permanent PCI scope of your whole network. Tokenize at the processor; never touch the number.
- Forgetting subprocessors. Your logging SaaS, error tracker, and email provider all touch personal data — each needs a DPA (and a BAA under HIPAA). The questionnaire asks; have the list.
- Delete means delete. A
deleted_atflag is not erasure. Propagate to replicas, indexes, streams, and backups — or crypto-shred the key.
Why does a data inventory precede any compliance control? A user invokes GDPR erasure — why is DELETE FROM users WHERE id = 77 insufficient, and how does crypto-shredding solve it? How does using a payment processor’s hosted fields change your PCI DSS obligations? Name the HIPAA mechanism that makes “who viewed this patient’s record?” answerable.
ASolution
Obligations attach to data, so you must know what PII exists, where it lives, and which regime governs it before you can protect, minimize, retain, or delete any of it — uninventoried fields are unprotected fields. Row deletion misses replicas, search indexes, event streams, warehouses, and backups; crypto-shredding encrypts each user’s data with a per-user key, so deleting the key renders every copy — including backups — permanently unreadable, satisfying erasure everywhere at once. With hosted fields, the PAN flows from the user’s browser directly to the processor and you store only a token, so your systems never handle cardholder data and your PCI scope shrinks to a self-assessment questionnaire instead of the full twelve requirements. HIPAA’s audit controls: named, immutable, reviewable logs recording who accessed which PHI, when, and why — minimum-necessary access made accountable.
End of the API Design course — fifteen chapters, from one HTTP request to an API that can answer a regulator.