Why encrypt in the application
The platform is a customer engagement service: each tenant sends email, SMS, WhatsApp and push messages to its own users. That means the database holds a lot of other people's personal data: email addresses, phone numbers, names, device tokens, and the messages themselves.
Disk or volume encryption protects against one threat, a stolen disk. It does nothing for the more likely ones: a database dump that ends up somewhere it should not, a backup copy, or a read-only database login used for reporting. Under India's DPDP Act 2023, any of those would count as a personal data breach.
So the data is encrypted per column, in the application, before it reaches Postgres. A dump, a backup or a read-only login now shows ciphertext.
Two primitives, two keys
1. Randomized encryption for storage
Every sensitive value is stored as a versioned token:
enc:v1:gAAAAABl... # Fernet: AES-128-CBC + HMAC-SHA256, random IV
Fernet is randomized: the same email encrypts differently every time, so ciphertext reveals nothing about which rows share a value. The enc:v1: prefix does two jobs: it marks a value as already encrypted (so encrypting twice is a no-op) and leaves room for a future format.
The model field decrypts on read, so templates, senders and serializers see plain text and most of the codebase did not change.
2. A blind index for lookups
Randomized encryption makes WHERE email = ? impossible. For the fields that are actually looked up, each table gets a second column with a keyed hash:
def blind_hash(kind, tenant_id, value):
normalized = normalize(kind, value) # "" for empty values
if not normalized:
return ""
msg = f"{kind}:{tenant_id}:{normalized}".encode()
return hmac.new(HASH_KEY, msg, hashlib.sha256).hexdigest() # 64 hex chars
Equality on the plain value becomes equality on the hash, which is a normal B-tree index lookup, the same shape as the plain index it replaces. Three details matter:
- It is an HMAC, not a plain hash. Phone numbers are a small space; a plain SHA-256 of every possible Indian mobile number takes minutes on one GPU. Without the key, the hash column is useless to an attacker.
- The tenant is in the input. The same email in two tenants produces two different hashes, so the hash column cannot be used to find one person across tenants.
- The kind names the value, not the column. A profile's
email_hashand a message'sto_email_hashboth use kindemail, so they are comparable without decrypting anything.
Normalize before hashing
Hashes only match if the inputs match exactly, so every kind is normalized first:
- email: trimmed and lowercased, so
A@Example.comanda@example.commatch, - phone: converted to E.164 with India as the default region, so
9876500001and+919876500001match, - names and other text: trimmed, whitespace collapsed, case-folded.
The encrypted column keeps the original spelling, for display and for sending.
What you give up, and how to fail safely
A blind index supports exactly three questions: equals, not equals, and has a value. Everything else is gone for encrypted fields: substring search, contains, ranges, sorting.
That broke real features, and each one needed a decision:
- Dashboard search became exact-match: a value with
@is looked up as an email hash, a value that parses as a phone number as a phone hash. Partial search on emails and names is gone. - Audience rules that used
containsor ranges on encrypted fields are rejected when saved. - Rules that were already saved with a removed operator fail closed: they match nobody, the preview shows the error, and any campaign or journey using them reports an issue. The alternative, silently matching everyone or skipping the condition, could message the wrong people.
- A management command lists every rule that would break, so they could be fixed before the change went out.
Free-form profile attributes are handled per tenant: each tenant marks which attribute keys hold personal data, and only those values are encrypted and hashed. A tenant cannot mark a key as personal if an existing rule depends on an operator that would stop working.
PII leaks through copies
Encrypting the profile table is the easy part. Personal data also gets copied, and every copy needs its own answer:
| Copy | Treatment |
|---|---|
| Message tables (recipient, subject, body, tracked links) | Encrypted, with hash columns for the recipient |
| "Identify" events that update a profile | Store that a field changed ("email": "[set]"), never the value; the profile is the only place it lives |
| Provider error text and journey failures | Partially masked at write time: as****@example.com, +91 98•••••210 |
| Application logs | Masked at the call site, plus a log formatter that masks any email or Indian mobile number that slips through, URL-encoded ones included |
| Idempotency keys that contained a raw push token | Replaced by a SHA-256 of the token |
Partial masking was a deliberate choice over full redaction. Support staff can still tell which recipient an error was about, and failure reasons still group together in reports because the masking is consistent.
Keys
There are two independent keys, both separate from the framework's secret key and from the key that protects stored provider credentials:
- Encryption keys are a list, newest first. Decryption tries each one (
MultiFernet), so rotation is: put a new key in front, restart, run a command that re-encrypts every stored value with the newest key, remove the old key. The same command has a--checkmode that only reports whether every stored value can still be decrypted. - The hash key is a single key. Changing it changes every hash, so lookups miss until every hash column is recomputed. It is rotated only if it leaks.
Staging and production refuse to start without valid keys. Both come from a secrets manager in the same region as the data (ap-south-1). And one fact went into the restore runbook in bold: losing the encryption keys loses the data. A backup without its keys is ciphertext.
Rolling it out
- Add the hash columns and switch the field types. The new field reads a value without the
enc:v1:prefix as plain text, so existing rows keep working before anything is encrypted. - Backfill in batches of 1,000 rows: encrypt each value, fill its hash. Already-prefixed values are skipped, so the migration can be re-run safely.
- Move the indexes from the plain columns to the hash columns and drop the old ones.
It shipped in four PRs: keys and profiles, per-tenant personal attributes, message tables, and finally the copies, error text and logs.
What it does not cover
Being precise about residual exposure matters more than the encryption itself:
- The external user id stays plain, because it is the join key for every analytics query on a partitioned events table. Some tenants use an email or phone number as that id. Hashing it is the next phase; until then, the advice to tenants is to send an opaque id.
- Custom event properties and task-queue payloads are not encrypted yet.
- The application itself sees plain text in memory and in dashboard responses. Role-based masking in the API handles the second part: lower roles see masked values, admins can reveal a field, and every reveal is written to an audit trail.
- Erasure still means deleting rows. Per-tenant keys for crypto-shredding were considered and left out.
Cost
Small by design. Fernet and HMAC-SHA256 each take microseconds per value. An identify request encrypts a handful of fields; a campaign decrypts one address per recipient while building sends. Hash lookups are B-tree lookups on 64-character columns, the same shape as the plain-text indexes they replaced.
Takeaways
- Encrypt in the application if your threat model includes dumps, backups or read-only database access.
- Use randomized encryption for storage and a keyed hash, scoped by tenant and normalized, for lookups.
- Decide up front which queries you will lose, and make old rules fail closed.
- Hunt down the copies: events, error text, logs and idempotency keys leak more than the main table.
- Write down what is still exposed. That list is what an auditor, and your future self, will ask for.