This resume is also available in English.

8. Security and working with AI2 / 12 · All columns

Columns › 8. Security and working with AI › Part 48

Field-Level Encryption in the Database: How to Encrypt, and How to Query Encrypted Data

欄位加密與資料庫:怎麼加密、加密後怎麼查詢

Disk encryption does not stop DBAs, leaked backups or SQL injection. This article covers which columns to encrypt in the application, AES-256-GCM nonces and AAD, envelope encryption with a KMS, equality search over ciphertext with blind indexes, the leakage cost of prefix, range and sort queries, and key rotation and migrating existing data.

  • Security
  • Encryption
  • PostgreSQL
  • Go
In this article
  1. What this article solves
  2. Step 1: What each layer of encryption stops
  3. Step 2: Which columns to encrypt, and which never to store
  4. Step 3: The algorithm: AES-256-GCM, nonces and AAD
  5. Step 4: Envelope encryption and a KMS: where keys come from
  6. Step 5: Implementing fieldcrypt in Go
  7. Step 6: Built-in database encryption, and when it fits
  8. Step 7: Equality search: blind indexes
  9. Step 8: What blind indexes leak, and how to reduce it
  10. Step 9: Prefix, range, sort and fuzzy search
  11. Step 10: Key rotation and background re-encryption
  12. Step 11: Going live and operating it
  13. Common pitfalls
  14. Key takeaways
  15. References
  16. Next

The previous article, “Microservice Security: Authentication, Authorisation, Secrets and Supply Chain”, dealt with "who may call which service" and "where secrets live". This article goes one layer down and answers a different question: if someone gets past those defences and reads the database directly, how much personal data can they see? The answer depends on whether the data is plaintext inside the database.

What this article solves

The shop's order service has a customers table holding recipients' email addresses, mobile numbers and postal addresses, and for some business customers a company tax ID and the contact person's national ID number. The database runs on managed PostgreSQL in the cloud with disk encryption on by default, and connections use TLS. It all looks safe, until someone asks a few questions:

  • A colleague in operations has a read-only account for reports and can run SELECT * FROM customers. Can they see everyone's mobile number? Yes.
  • The nightly pg_dump backup is copied to another storage bucket whose permissions were set wrong. What is in the leaked file? Everything, in plaintext.
  • An admin back-office query has a SQL injection. Can an attacker read the whole table with UNION SELECT? Yes, in plaintext.
  • The data is synced to an analytics platform and printed into slow query logs. Who looks after those copies? Nobody knows.

Disk encryption helps with none of these, because the data the database process reads has already been decrypted. To make these cases yield only ciphertext, the data must be encrypted in the application, before it reaches the database: field-level encryption. But once it is encrypted, the database no longer understands the column: WHERE email = $1 stops working, unique constraints are useless and sorting means nothing. This article answers both halves:

  1. What each of the three layers (transport, disk, field) protects against, and why the third is needed.
  2. Which columns to encrypt, which never to store, and how encryption, hashing, tokenisation and masking differ.
  3. Choosing the algorithm: AES-256-GCM, nonce uniqueness, and AAD that ties a ciphertext to one column of one row.
  4. Where keys come from: envelope encryption with a KMS, with the key version recorded in the ciphertext.
  5. A tested fieldcrypt package in Go.
  6. When the database's built-in encryption functions and TDE are appropriate.
  7. Querying after encryption: blind indexes for equality search and unique constraints.
  8. What blind indexes leak, and reducing it with truncation.
  9. Whether prefix, range, sort and fuzzy search are possible, and at what cost.
  10. Key rotation and background re-encryption.
  11. Migrating existing data, logs, backups, auditing and performance.

Step 1: What each layer of encryption stops

"The data is encrypted" means at least three different things, with completely different coverage:

Client order service PostgreSQL Disk / backup TLS (in transit) Disk encryption / TDE Ciphertext App field encryption Ciphertext (only order can decrypt) TLS: stops eavesdropping on the wire; each end sees plaintext. Disk/TDE: stops a stolen disk or snapshot; the database process, query results and pg_dump see plaintext. Field encryption: DBAs, backup files, rows read by SQL injection and analytics copies all hold ciphertext. The cost: the database can no longer read the column, so querying, sorting and indexing need redesigning.

Figure: TLS is ciphertext only in transit and disk encryption only in data files; only application-level field encryption keeps plaintext away from everything outside the order service.

LayerWhere it encrypts and decryptsStopsDoes not stop
TLSBoth ends of a connectionEavesdropping and tampering on the networkAnyone at either end; data is plaintext once it reaches the database
Disk / TDEStorage layer (disk, cloud volume, database engine)Stolen disks, leaked snapshots, scrapped hardwareAnything that can connect: DBAs, app accounts, SQL injection, pg_dump
Application fieldThe service that owns the dataAll of the above, plus DBAs, backups, data copiesCompromise of the service that holds the key

Going through the threats one by one makes it clearer what field encryption adds:

Who can read the plaintext email? TLS Disk / TDE Field encryption Sniffing the internal network Blocked Exposed Blocked Stolen disk or snapshot Exposed Blocked Blocked Leaked backup file or pg_dump Exposed Exposed Blocked DBA or read-only DB account Exposed Exposed Blocked SQL injection dumping a table Exposed Exposed Partly Copies in analytics and logs Exposed Exposed Partly order service itself compromised Exposed Exposed Exposed Partly: if the injection is in the service that decrypts, or the code logs plaintext itself, encryption cannot help. Field encryption narrows who can read to the service holding the key; that is its one and most important value.

Figure: only field encryption stops the first four threats; SQL injection and data copies are "partly" because an injection in the decrypting service, or code that logs plaintext itself, defeats encryption; if the order service itself is compromised, none of the three layers helps.

When it fits: several people or systems can read the database (DBAs, reporting accounts, data sync), backups are copied elsewhere, and a leak would be serious (national ID numbers, bank accounts). Why it is needed: it shrinks "who can read plaintext" from "everything that can connect to the database" to "the one service holding the key", which the other two layers cannot do.

When it is not needed: the data is not sensitive (product names, stock levels); or the whole database is used by a single service and account, backups are encrypted and tightly controlled, in which case disk encryption plus access control may be enough. Field encryption has real costs: harder queries, more complex migrations and key management. Do not encrypt every column.

Keep transport and disk encryption on. They are cheap, have almost no side effects, and cover what field encryption does not (other unencrypted columns, metadata). The three layers stack; they are not alternatives.

Step 2: Which columns to encrypt, and which never to store

List the columns in customers and related tables and decide one by one:

ColumnSensitivityNeed to query?Recommendation
National ID numberVery highOccasional equality (support verification)Encrypt + blind index; better still, do not collect it
Mobile numberHighEquality, last-four-digit searchEncrypt + blind index + truncated last-four index
EmailHighLogin, uniqueness, equalityEncrypt + blind index (unique)
Postal addressHighRarely queried, only displayedEncrypt; keep a non-sensitive city column for stats
Bank account (for refunds)Very highNot queriedEncrypt; display only the last five digits
Card numberExtreme—Do not store it; let the payment provider tokenise
Date of birthMediumStatistics by age bandEncrypt; keep birth year or age band separately
Gender, membership tierLowFiltering, statisticsDo not encrypt (it would not hide anything; see Step 8)

Card numbers are a special case. “Payment Pitfalls: Double Charges, Callbacks and Reconciliation” already made the point: the best approach is for the card number never to pass through our servers at all, using the payment provider's hosted payment page or hosted fields and keeping only the token the provider returns. Encrypting card numbers and storing them yourself is still "storing card numbers", and it pulls the whole system into the scope of the Payment Card Industry Data Security Standard (PCI DSS); and the card verification code (CVV) must not be stored after authorisation at all, encrypted or not.

On regulation: Taiwan's Personal Data Protection Act requires organisations that hold personal data to take appropriate security measures to prevent it being stolen, altered, damaged, lost or leaked, and PCI DSS requires stored card numbers to be unreadable wherever they are kept. Regulations generally do not prescribe a particular kind of encryption; how far you need to go is for your legal and audit functions to judge. What engineering can do is make "only the services that need it can read plaintext" something you can demonstrate.

Encryption is not the only tool for sensitive data. Four approaches that are often confused:

ApproachReversible?Queryable?Good forNot for
Encryption (AES-GCM)Yes, with the keyNot directlyValues you must read back: emails, shipping, support screensData you only compare and never read back
Hashing (incl. HMAC)NoEquality comparisonPasswords (with a slow hash such as bcrypt or argon2), blind indexesValues you must read back
TokenisationOnly the token service can map backEquality on the tokenCard numbers via the payment provider; a central PII vaultSmall systems: one more critical dependency
MaskingNo (display only)—Screens and logs showing 0912***678Protecting storage: masking is only display

In practice they are combined: the mobile number is stored encrypted, queried through an HMAC blind index and shown masked on the support screen.

Step 3: The algorithm: AES-256-GCM, nonces and AAD

The default choice for field encryption is AES-256-GCM. It is an AEAD (authenticated encryption with associated data), providing confidentiality and integrity together. If a single bit of the ciphertext has been changed, decryption fails outright instead of returning garbage for the program to carry on with. Go's standard library has it in crypto/aes and crypto/cipher; no third-party package is needed.

GCM comes with three rules:

A nonce must never repeat under the same key. The GCM nonce is 12 bytes (96 bits). If two values under one key share a nonce, an attacker gets the XOR of the two plaintexts and can forge ciphertexts that pass authentication. Field encryption writes happen across many instances and restarts, so maintaining a never-repeating counter is hard; the usual choice is a random nonce from crypto/rand each time. Random nonces have a birthday-collision problem, and the Go standard library documentation gives the limit for GCM with random nonces: do not encrypt more than 2^32 messages with one key. For a customer table that is far away, but it is one more reason to rotate keys regularly (Step 10).

Use AAD to tie a ciphertext to its location. AAD (additional authenticated data) is not encrypted but is authenticated. Without AAD, someone with write access to the database could copy customer A's email_ct into their own row: the ciphertext is valid, the application decrypts it as usual, and shows A's email on the attacker's account page or sends notifications to A's inbox. With "table + column + row ID" in the AAD, a ciphertext moved elsewhere will not decrypt. This requires the row ID to be known before encryption, so IDs should be generated by the application (UUID, ULID or your own format) rather than taken from a database sequence after INSERT.

Do not invent your own. Do not use ECB mode (identical plaintext blocks give identical ciphertext blocks, exposing the structure); do not use CBC without a MAC; do not treat SHA-256 as encryption; do not assemble "AES plus some checksum" yourself. Use the standard library's AEAD or a mature high-level library (such as Google Tink), and decide only the format and key management.

ChoiceWhenWatch out
AES-256-GCM + random nonceDefault; in Go's standard library and every language, hardware-acceleratedAt most 2^32 values per key; a nonce must never repeat
ChaCha20-Poly1305 / XChaCha20No AES hardware acceleration; XChaCha's 24-byte nonce is safer to randomiseIn golang.org/x/crypto, not the standard library
AES-SIV (deterministic)You need "same plaintext → same ciphertext" for equality (Step 9)Leaks equality; not in Go's standard library or x/crypto, use something like Tink
AES-ECB, home-made combinationsNever—

Go's standard library also has cipher.NewGCMWithRandomNonce, which generates the nonce and puts it in front of the ciphertext. This article handles the nonce itself so that the stored format is obvious in the next diagram; the two are equally secure.

Step 4: Envelope encryption and a KMS: where keys come from

The encryption key must not sit with the data, nor in a config file. The mainstream approach is envelope encryption:

  • The master key (KEK, key encryption key) lives in a KMS (AWS KMS, GCP Cloud KMS, HashiCorp Vault's Transit engine and so on) and never leaves it.
  • The data key (DEK, data encryption key) is the 32-byte key that actually encrypts columns. It is stored only after being "wrapped" (encrypted) by the master key, in configuration, a Secret or a key table.
  • At startup the service sends the wrapped DEK to the KMS to be unwrapped, keeps the plaintext DEK in memory, and does all encryption and decryption locally after that.
KMS Master key (KEK) never leaves the KMS Config / Secret Wrapped DEKs v1, v2: useless on their own order service (memory) DEK v1, DEK v2 encrypt v2, decrypt any PostgreSQL v2 | nonce | ct | tag version stored per value ① read at startup ② KMS unwraps returns plain DEK ③ encrypt The KMS only ever handles 32-byte data keys, never the personal data itself; data keys are cached in memory, so no KMS call is needed per operation.

Figure: the master key stays in the KMS; the order service asks the KMS to unwrap its data keys at startup, then encrypts in memory, recording the key version in front of each ciphertext.

The corresponding KMS operations: AWS KMS's GenerateDataKey returns a plaintext and a wrapped data key in one call, and Decrypt unwraps it; GCP Cloud KMS has no dedicated data-key call, so you generate the DEK locally with crypto/rand and wrap it with the key's Encrypt, unwrapping with Decrypt; Vault Transit has a datakey endpoint to generate data keys, decrypt to unwrap them, and rewrap to re-wrap them after the master key rotates.

Why it is needed:

  • The KMS only touches 32-byte keys, never personal data. Personal data never leaves the service and is not subject to the KMS's request size, rate limits or latency.
  • Access control and audit are centralised. "Who may unwrap the DEK" is decided by the KMS's IAM policy, and every unwrap is logged; only the order service's identity may call Decrypt. Stealing the database and the wrapped DEK gets you nothing.
  • Rotating the master key is cheap. It only means re-wrapping a few DEKs, not re-encrypting millions of rows.

Cache the data keys. Do not call the KMS for every encryption: that adds a network round trip to each query, puts you under the KMS's rate limits, and takes the service down whenever the KMS fails. Unwrapping at startup and keeping the keys in memory is what this article does; the price is plaintext keys in memory, so containers should not allow core dumps or debugger attachment. If the KMS is unavailable at startup, treat it like the other dependencies in “Configuration and Graceful Shutdown in Go”: retry a few times, then fail to start and let Kubernetes restart the pod, rather than serving traffic without keys.

When a KMS is not needed: a small system or single service can start by treating the DEK as an ordinary secret, mounted as a file as in the previous article. That is still better than plaintext, but "steal the Secret and you can decrypt everything", and there is no decryption audit trail. Move to a KMS as volume and sensitivity grow; as long as the Keyring interface stays the same, the encryption code does not change.

Record the key version with every ciphertext. Keys will be changed one day. If the ciphertext does not say which key encrypted it, then while old and new data are mixed during rotation the program can only try keys one by one. So every ciphertext starts with its key version, and decryption goes straight to the right key.

Step 5: Implementing fieldcrypt in Go

These decisions become a small package, internal/fieldcrypt. The stored format:

email_ct (bytea) fmt 1 B key ver 4 B nonce 12 B, random ciphertext same length as plaintext tag 16 B AAD = fmt + version + table + column + row ID not stored; rebuilt by the code on decrypt tag covers AAD + ct customers table id text key_version int email_ct bytea email_bidx 32 B unique phone_ct bytea phone_bidx 32 B phone_last4_bidx 2 B Only the order service can decrypt the highlighted columns; blind index columns are for lookup and cannot be reversed.

Figure: one bytea column holds format, key version, nonce, ciphertext and tag in order; the AAD is built from format, version, table, column and row ID and is not stored; the blind index used for lookups is a separate column.

The format byte lets a future change of algorithm or layout (say, to XChaCha20) be recognised; the key version and format are also part of the AAD, so tampering with them makes decryption fail. Each value is 33 bytes longer than its plaintext (1 + 4 + 12 + 16).

The Keyring interface is the seam for the KMS: the production implementation unwraps every DEK version with the KMS at startup; the test StaticKeyring takes plaintext keys directly.

// Package fieldcrypt encrypts single columns in the application: AES-256-GCM, a random nonce,
// "table + column + row ID" as AAD, and the key version recorded in front of the ciphertext.
package fieldcrypt

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/binary"
	"errors"
	"fmt"
)

// Stored format: | format 1 byte | key version 4 bytes | nonce 12 bytes | ciphertext | tag 16 bytes |
const (
	formatV1   byte = 1
	headerSize      = 1 + 4
	nonceSize       = 12
	tagSize         = 16
)

var ErrDecrypt = errors.New("fieldcrypt: decrypt failed")

// Keyring provides data keys: Current encrypts new data, AEAD finds older keys by version for decryption.
// A production implementation unwraps the data keys with the KMS at startup and keeps them in memory.
type Keyring interface {
	Current() (version uint32, aead cipher.AEAD)
	AEAD(version uint32) (cipher.AEAD, error)
}

// StaticKeyring is an in-memory Keyring standing in for data keys already unwrapped by the KMS.
type StaticKeyring struct {
	current uint32
	aeads   map[uint32]cipher.AEAD
}

// NewStaticKeyring takes "version -> 32-byte key"; current must be among them.
func NewStaticKeyring(current uint32, keys map[uint32][]byte) (*StaticKeyring, error) {
	if _, ok := keys[current]; !ok {
		return nil, fmt.Errorf("fieldcrypt: current key version %d missing", current)
	}
	k := &StaticKeyring{current: current, aeads: make(map[uint32]cipher.AEAD, len(keys))}
	for v, key := range keys {
		if len(key) != 32 {
			return nil, fmt.Errorf("fieldcrypt: key version %d is %d bytes, want 32", v, len(key))
		}
		block, err := aes.NewCipher(key)
		if err != nil {
			return nil, err
		}
		aead, err := cipher.NewGCM(block)
		if err != nil {
			return nil, err
		}
		k.aeads[v] = aead
	}
	return k, nil
}

func (k *StaticKeyring) Current() (uint32, cipher.AEAD) { return k.current, k.aeads[k.current] }

func (k *StaticKeyring) AEAD(version uint32) (cipher.AEAD, error) {
	a, ok := k.aeads[version]
	if !ok {
		return nil, fmt.Errorf("fieldcrypt: unknown key version %d", version)
	}
	return a, nil
}

// Context binds a ciphertext to where it lives; moved to another row or column, it will not decrypt.
type Context struct {
	Table, Column, RowID string
}

func (c Context) aad(header []byte) []byte {
	// Table and column names are constants in code without NUL, so NUL is a safe separator.
	b := append([]byte{}, header...)
	return append(b, c.Table+"\x00"+c.Column+"\x00"+c.RowID...)
}

// Encrypt uses the current key version and a fresh random nonce every time.
func Encrypt(kr Keyring, plaintext []byte, ctx Context) ([]byte, error) {
	version, aead := kr.Current()
	out := make([]byte, headerSize+nonceSize, headerSize+nonceSize+len(plaintext)+tagSize)
	out[0] = formatV1
	binary.BigEndian.PutUint32(out[1:headerSize], version)
	nonce := out[headerSize:]
	if _, err := rand.Read(nonce); err != nil {
		return nil, err
	}
	return aead.Seal(out, nonce, plaintext, ctx.aad(out[:headerSize])), nil
}

// Decrypt finds the key by the recorded version; a wrong ciphertext, version or Context makes it fail.
func Decrypt(kr Keyring, stored []byte, ctx Context) ([]byte, error) {
	version, err := KeyVersion(stored)
	if err != nil {
		return nil, err
	}
	aead, err := kr.AEAD(version)
	if err != nil {
		return nil, err
	}
	nonce := stored[headerSize : headerSize+nonceSize]
	pt, err := aead.Open(nil, nonce, stored[headerSize+nonceSize:], ctx.aad(stored[:headerSize]))
	if err != nil {
		return nil, ErrDecrypt
	}
	return pt, nil
}

// KeyVersion reports which key version a ciphertext uses, without decrypting.
func KeyVersion(stored []byte) (uint32, error) {
	if len(stored) < headerSize+nonceSize+tagSize || stored[0] != formatV1 {
		return 0, ErrDecrypt
	}
	return binary.BigEndian.Uint32(stored[1:headerSize]), nil
}

// Reencrypt is for rotation: a value already on the current version is returned as is with changed=false.
func Reencrypt(kr Keyring, stored []byte, ctx Context) (out []byte, changed bool, err error) {
	v, err := KeyVersion(stored)
	if err != nil {
		return nil, false, err
	}
	if cur, _ := kr.Current(); v == cur {
		return stored, false, nil
	}
	pt, err := Decrypt(kr, stored, ctx)
	if err != nil {
		return nil, false, err
	}
	out, err = Encrypt(kr, pt, ctx)
	return out, err == nil, err
}

The tests must prove every claim this article makes: a round trip works, flipping any single bit fails, moving to another row or column fails, ten thousand encryptions all get different nonces, and after rotation the old version still decrypts and can be re-encrypted. Two of them are below (the full tests also cover tampering, nonce uniqueness, blind indexes and normalisation):

// fragment: fieldcrypt_test.go
func TestSwappedRowFails(t *testing.T) {
	kr, _ := NewStaticKeyring(1, map[uint32][]byte{1: key32(t)})
	ct, _ := Encrypt(kr, []byte("alice@example.com"), ctx)
	other := []Context{
		{Table: "customers", Column: "email", RowID: "c-1002"},
		{Table: "customers", Column: "phone", RowID: "c-1001"},
	}
	for _, o := range other {
		if _, err := Decrypt(kr, ct, o); !errors.Is(err, ErrDecrypt) {
			t.Fatalf("decrypt with %+v: want ErrDecrypt, got %v", o, err)
		}
	}
}

func TestRotation(t *testing.T) {
	k1, k2 := key32(t), key32(t)
	old, _ := NewStaticKeyring(1, map[uint32][]byte{1: k1})
	ct1, _ := Encrypt(old, []byte("A123456789"), ctx)

	// Rotation: new data uses version 2, old version 1 only decrypts.
	kr, _ := NewStaticKeyring(2, map[uint32][]byte{1: k1, 2: k2})
	if pt, err := Decrypt(kr, ct1, ctx); err != nil || string(pt) != "A123456789" {
		t.Fatalf("old version: %q, %v", pt, err)
	}
	ct2, changed, err := Reencrypt(kr, ct1, ctx)
	if err != nil || !changed {
		t.Fatalf("reencrypt: changed=%v err=%v", changed, err)
	}
	if v, _ := KeyVersion(ct2); v != 2 {
		t.Fatalf("version %d, want 2", v)
	}
	if _, changed, _ := Reencrypt(kr, ct2, ctx); changed {
		t.Fatal("already current, should not change")
	}
	// Once version 1 is removed, old ciphertext cannot be decrypted: remove it only after re-encryption finishes.
	only2, _ := NewStaticKeyring(2, map[uint32][]byte{2: k2})
	if _, err := Decrypt(only2, ct1, ctx); err == nil {
		t.Fatal("version 1 should be gone")
	}
}
go vet ./... && go test ./internal/fieldcrypt/

Note the end of TestRotation: once the old version is removed from the Keyring, data not yet re-encrypted can never be decrypted again. This is where key rotation most often goes wrong; Step 10 returns to it.

Step 6: Built-in database encryption, and when it fits

If we are encrypting anyway, why not use the database's own features? The common options:

OptionHowStops DBAs / SQL injection?Fits
Cloud disk or file system encryptionStorage layer encrypts, transparent to the databaseNoAlways on
TDE (transparent data encryption)The database engine encrypts when writing filesNoRegulation demands "encryption at rest"; leaked data files
PostgreSQL pgcrypto (e.g. pgp_sym_encrypt)Call a function in SQL, passing the key as a parameterPartlyTemporary, low-volume, when the application cannot change
MySQL AES_ENCRYPT()SamePartlySame; mind the default block mode
Application-level field encryptionEncrypt in the service, the database stores ciphertextYesThis article's default

TDE and disk encryption are fully transparent to anything that can connect, so they do not stop DBAs, SQL injection or pg_dump. They still have value (stolen disks, snapshots, backup tapes) but solve a different problem. Official PostgreSQL has no built-in TDE and generally relies on cloud or operating system disk encryption; some commercial distributions offer TDE. MySQL's InnoDB has tablespace encryption.

The problem with pgcrypto is the key's path. pgp_sym_encrypt(data, key) runs inside the database server, so both plaintext and key travel into the database as SQL parameters. If the database's statement log, slow query log, error messages or monitoring tools record parameters, the key and plaintext stay there; a DBA can also see them pass through the server. The "Security Limitations" section of the PostgreSQL pgcrypto documentation says as much: data and passwords move between pgcrypto and client applications in clear text, so you must trust both the system and database administrators, and if you cannot, it is better to do the crypto inside the client application. It stops someone who only steals data files or backups, but not someone who can see the database server, which is exactly who we care most about.

MySQL's AES_ENCRYPT() has the same key-path problem; in addition its block mode comes from the block_encryption_mode system variable, whose default is aes-128-ecb, the ECB that Step 3 said not to use. If you must use it, at least switch to a mode with an IV, but you still get no integrity protection.

Conclusion: always turn on disk encryption; for sensitive columns, encrypt in the application and let the database just store bytea. The database's built-in encryption functions suit transitional situations such as "we cannot change the code yet but want to reduce the risk of leaked backups".

Step 7: Equality search: blind indexes

After encryption, WHERE email = 'alice@example.com' no longer works: the same email gets a different nonce, and so a different ciphertext, every time. But the business still needs:

  • Login and registration: find a customer by email, and allow each email to register only once.
  • Support: a customer phones in with their mobile number and support must find their orders.

The technique is a blind index: store an extra column next to the ciphertext containing HMAC-SHA256(blind index key, normalised value). To query, compute the index value with the same key and the same normaliser, and use an equality condition.

Support types " Alice@Example.COM " Normalise alice@example.com HMAC-SHA256 blind index key (separate) SQL WHERE email_bidx = $1 PostgreSQL unique index → c-1001 Decrypt AAD includes c-1001 Return to support log only c-1001 The database only sees a 32-byte hash; the lookup uses an ordinary B-tree index, as fast as plaintext equality. Without the blind index key, nobody can compute index values, so guessed emails cannot be tested against the table. Writes and lookups must share one normaliser, or the same email produces different index values.

Figure: the email typed by support is normalised, then an HMAC is computed with a separate blind index key; the database finds one row through an ordinary unique index, and the order service decrypts it with the AAD.

Every design choice has a reason:

  • HMAC, not plain SHA-256. There are only a hundred million possible Taiwan mobile numbers; anyone with the database can compute SHA-256(mobile) for all of them in a short time and reverse the lookup. HMAC needs a key, and without it nobody can compute index values or test guesses against them.
  • A blind index key separate from the encryption key. They serve different purposes and rotate differently (Step 10); keeping them separate also lets "can search" and "can decrypt" be different permissions.
  • Normalise first. Alice@Example.COM and alice@example.com are the same person; 0912-345-678 and +886 912 345 678 are the same phone. Get the normalisation wrong and one value gets several index values, so the unique constraint no longer stops duplicate registrations. Phones go to E.164 (+886912345678); emails are trimmed and lowercased. Do not strip Gmail dots or +tag on your own initiative: those are business rules, not format.
  • Add a domain. Putting "table.column" into the HMAC gives the same value different index values in different columns, so values cannot be matched across columns.
package fieldcrypt

import (
	"crypto/hmac"
	"crypto/sha256"
	"errors"
	"strings"
)

// BlindIndex computes HMAC-SHA256 over a normalised value and keeps the first bits bits (1 to 256).
// key must be separate from the encryption keys; domain is "table.column", so one value gets different indexes in different columns.
func BlindIndex(key []byte, domain, normalised string, bits int) []byte {
	if bits < 1 || bits > 256 {
		panic("fieldcrypt: bits must be 1..256")
	}
	mac := hmac.New(sha256.New, key)
	mac.Write([]byte(domain))
	mac.Write([]byte{0})
	mac.Write([]byte(normalised))
	sum := mac.Sum(nil)
	out := sum[:(bits+7)/8]
	if r := bits % 8; r != 0 {
		out[len(out)-1] &= 0xFF << (8 - r) // clear the low bits beyond bits
	}
	return out
}

var ErrInvalid = errors.New("fieldcrypt: invalid input")

// NormaliseEmail trims and lowercases. It keeps Gmail dots and +tags: those are business rules, not format.
func NormaliseEmail(s string) (string, error) {
	s = strings.ToLower(strings.TrimSpace(s))
	at := strings.IndexByte(s, '@')
	if at <= 0 || at != strings.LastIndexByte(s, '@') || at == len(s)-1 {
		return "", ErrInvalid
	}
	return s, nil
}

// NormaliseTWMobile turns a Taiwan mobile number into E.164, e.g. 0912-345-678 → +886912345678.
func NormaliseTWMobile(s string) (string, error) {
	var b strings.Builder
	for _, r := range s {
		switch {
		case r >= '0' && r <= '9', r == '+':
			b.WriteRune(r)
		case r == ' ', r == '-', r == '(', r == ')', r == '.':
		default:
			return "", ErrInvalid
		}
	}
	d := b.String()
	switch {
	case strings.HasPrefix(d, "+886"):
		d = strings.TrimPrefix(d[4:], "0") // some people write +886 0912…
	case strings.HasPrefix(d, "886"):
		d = strings.TrimPrefix(d[3:], "0")
	case strings.HasPrefix(d, "0"):
		d = d[1:]
	}
	if len(d) != 9 || d[0] != '9' || strings.ContainsRune(d, '+') {
		return "", ErrInvalid
	}
	return "+886" + d, nil
}

The table stores ciphertext and blind indexes separately, and the unique constraint moves to the blind index:

CREATE TABLE customers (
    id               text PRIMARY KEY,
    key_version      integer NOT NULL,        -- key version used by this row; lets the rotation job find rows
    email_ct         bytea   NOT NULL,        -- format | key version | nonce | ciphertext | tag
    email_bidx       bytea   NOT NULL,        -- HMAC-SHA256(normalised email), 32 bytes
    phone_ct         bytea,
    phone_bidx       bytea,                   -- HMAC-SHA256(E.164)
    phone_last4_bidx bytea,                   -- HMAC of the last 4 digits, 16 bits kept
    created_at       timestamptz NOT NULL DEFAULT now(),
    CONSTRAINT email_bidx_len CHECK (octet_length(email_bidx) = 32)
);

-- One registration per email: uniqueness is now enforced by the blind index.
CREATE UNIQUE INDEX customers_email_bidx_uq ON customers (email_bidx);
CREATE INDEX customers_phone_bidx_idx ON customers (phone_bidx);
CREATE INDEX customers_phone_last4_bidx_idx ON customers (phone_last4_bidx);
CREATE INDEX customers_key_version_idx ON customers (key_version);

To query, the application computes the index value and passes it as a parameter:

SELECT id, email_ct FROM customers WHERE email_bidx = $1;

This was checked against PostgreSQL 17 with real ciphertexts and index values: the query uses an Index Scan on customers_email_bidx_uq, and a duplicate email is rejected by the unique index (duplicate key value violates unique constraint).

The order service's query code:

// Package customer shows blind index lookups and background re-encryption.
package customer

import (
	"context"
	"database/sql"
	"errors"
	"log/slog"

	"example.com/shop/fieldcrypt"
)

// PII is decrypted personal data; slog redacts it automatically.
type PII string

func (PII) LogValue() slog.Value { return slog.StringValue("[REDACTED]") }

var ErrNotFound = errors.New("customer: not found")

type Repo struct {
	DB   *sql.DB
	Keys fieldcrypt.Keyring
	BIK  []byte // blind index key, separate from the encryption keys
}

// FindByEmail normalises, computes the blind index, finds the row by it and then decrypts.
func (r *Repo) FindByEmail(ctx context.Context, email string) (id string, plain PII, err error) {
	norm, err := fieldcrypt.NormaliseEmail(email)
	if err != nil {
		return "", "", err
	}
	bidx := fieldcrypt.BlindIndex(r.BIK, "customers.email", norm, 256)
	var ct []byte
	err = r.DB.QueryRowContext(ctx,
		`SELECT id, email_ct FROM customers WHERE email_bidx = $1`, bidx).Scan(&id, &ct)
	if errors.Is(err, sql.ErrNoRows) {
		return "", "", ErrNotFound
	}
	if err != nil {
		return "", "", err
	}
	pt, err := fieldcrypt.Decrypt(r.Keys, ct, fieldcrypt.Context{Table: "customers", Column: "email", RowID: id})
	if err != nil {
		return "", "", err
	}
	return id, PII(pt), nil
}

// FindByPhoneLast4 queries a 16-bit truncated index; results must be decrypted and compared again to drop collisions.
func (r *Repo) FindByPhoneLast4(ctx context.Context, last4 string) ([]string, error) {
	bidx := fieldcrypt.BlindIndex(r.BIK, "customers.phone_last4", last4, 16)
	rows, err := r.DB.QueryContext(ctx,
		`SELECT id, phone_ct FROM customers WHERE phone_last4_bidx = $1 LIMIT 200`, bidx)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var ids []string
	for rows.Next() {
		var id string
		var ct []byte
		if err := rows.Scan(&id, &ct); err != nil {
			return nil, err
		}
		pt, err := fieldcrypt.Decrypt(r.Keys, ct, fieldcrypt.Context{Table: "customers", Column: "phone", RowID: id})
		if err != nil {
			return nil, err
		}
		if p := string(pt); len(p) >= 4 && p[len(p)-4:] == last4 {
			ids = append(ids, id)
		}
	}
	return ids, rows.Err()
}

// ReencryptBatch re-encrypts one batch of old-version rows with the current key and returns how many it handled; 0 means done.
// One short transaction per batch; SKIP LOCKED lets several workers run in parallel without blocking live writes.
func (r *Repo) ReencryptBatch(ctx context.Context, limit int) (int, error) {
	cur, _ := r.Keys.Current()
	tx, err := r.DB.BeginTx(ctx, nil)
	if err != nil {
		return 0, err
	}
	defer tx.Rollback()

	rows, err := tx.QueryContext(ctx, `
		SELECT id, email_ct, phone_ct FROM customers
		WHERE key_version < $1 ORDER BY id LIMIT $2
		FOR UPDATE SKIP LOCKED`, cur, limit)
	if err != nil {
		return 0, err
	}
	type row struct {
		id           string
		email, phone []byte
	}
	var batch []row
	for rows.Next() {
		var x row
		if err := rows.Scan(&x.id, &x.email, &x.phone); err != nil {
			rows.Close()
			return 0, err
		}
		batch = append(batch, x)
	}
	rows.Close()
	if err := rows.Err(); err != nil {
		return 0, err
	}

	for _, x := range batch {
		email, _, err := fieldcrypt.Reencrypt(r.Keys, x.email, fieldcrypt.Context{Table: "customers", Column: "email", RowID: x.id})
		if err != nil {
			return 0, err
		}
		phone := x.phone // phone may be NULL
		if phone != nil {
			if phone, _, err = fieldcrypt.Reencrypt(r.Keys, x.phone, fieldcrypt.Context{Table: "customers", Column: "phone", RowID: x.id}); err != nil {
				return 0, err
			}
		}
		if _, err := tx.ExecContext(ctx,
			`UPDATE customers SET email_ct = $1, phone_ct = $2, key_version = $3 WHERE id = $4`,
			email, phone, cur, x.id); err != nil {
			return 0, err
		}
	}
	return len(batch), tx.Commit()
}

FindByPhoneLast4 and ReencryptBatch are explained in Steps 8 and 10. All three methods were run in an integration test against a throwaway PostgreSQL container (insert three rows, look up by email and last four digits, look up again after rotation).

When it fits: exact-match lookups on email, mobile, national ID or company tax ID, and unique constraints. When it does not: columns that need partial matching, ranges or sorting (Step 9), and columns with few distinct values (Step 8).

Step 8: What blind indexes leak, and how to reduce it

Blind indexes are not free. Someone with the database cannot compute index values, but can see:

  • Which rows have equal values. If two orders share a phone_bidx, they share a phone.
  • How often each value appears. If one index value appears in ten thousand rows, outside knowledge (such as the most common values) can reveal what it is.

This frequency analysis is especially damaging for columns with few distinct values. Gender has a handful of values, membership tiers four, birthdays within a century about thirty-six thousand: give such a column a full blind index, and an attacker who knows one person's value can mark everyone who shares it; even without that, the distribution gives it away. So:

  • No blind indexes on low-entropy columns. Gender and tier should not be encrypted to "look secure"; if they need filtering, store them in plaintext and accept that they are not secret.
  • Columns like birthdays that feed statistics: encrypt the original, and store a coarse non-sensitive column (birth year, age band) for queries.
  • A leaked blind index key turns the index into plaintext. With the key, an attacker can compute the HMAC of all hundred million mobile numbers and compare. Protect the blind index key as well as the encryption key, and manage it in the KMS.

Truncation is the tool for reducing leakage. HMAC produces 256 bits; keep only the first few and many different values land on the same index value. Support often finds people by "the last four digits of the mobile", which has only ten thousand possibilities:

  • Store all 256 bits and anyone can split the data into ten thousand groups by last four digits, each group sharing them exactly.
  • Store only 16 bits (65,536 values) and the ten thousand possibilities spread across them while query results stay small; this article's tests check that the truncated length is right and that ten thousand distinct last-four values really do collide at 16 bits.
  • Go shorter, say 8 bits (256 values), and each index value covers about 40 possible last-four values; the index no longer reveals the digits, but every query pulls back many unrelated rows.

The cost of truncation is false positives: results include non-matching rows, so FindByPhoneLast4 must decrypt and compare again after fetching, with a LIMIT. A truncated index also cannot carry a unique constraint; uniqueness belongs on a full-length index. Choose the bit length from your data volume: too long leaks more, too short means decrypting too many rows per query. A rough starting point is for each index value to cover tens to hundreds of rows on average.

CipherSweet is a published blind index design that includes truncation and "one index built from several columns"; it is a useful reference when designing your own scheme.

Beyond equality, every other kind of query costs more leakage, or cannot be done at all:

Query How What leaks Advice Equality, unique WHERE bidx = $1 Blind index (HMAC) which rows are equal, and how often Use it Prefix, partial LIKE 'abc%' Several n-gram or truncated indexes frequency and overlap of every piece Only if truly needed Range, sort BETWEEN, ORDER BY OPE / ORE the order of values, often the values Avoid; keep a coarse non-secret column Any substring LIKE '%abc%' No good scheme — Use a separate search service Aggregates SUM, GROUP BY Decrypt and compute in the app nothing, but reads every row Small data only Rule: if equality solves the need, do not build fuzzy search; every extra query capability is extra leakage.

Figure: equality works with a blind index; prefix works with several n-gram blind indexes at a higher leakage cost; OPE/ORE for range and sort leak order and are generally avoided; arbitrary substrings go to a separate service; aggregates are computed in the application after decryption.

Prefix and partial matching: you can store several blind indexes per value, for example one each for the first 3, 4 and 5 characters of an email, or one for each 3-gram of a phone number, and compute the index of the matching piece at query time. This supports "find it after typing the first few characters", but every piece leaks frequency, and the relationships between pieces (which rows share the first 3 characters and also the first 4) let an attacker piece together more. Do it only when truly needed, and always truncate.

Range and sort: order-preserving encryption (OPE) gives ciphertexts the same order as their plaintexts, and order-revealing encryption (ORE) lets two ciphertexts be compared. They let BETWEEN and ORDER BY run in the database, but order itself is a lot of information: know the order of ten thousand birthdays and roughly their distribution, and you can infer values close to the originals. The general advice is not to use them. Alternatives:

  • Store a coarse, non-sensitive column: birth year, age band, city, amount band. Reports and filters use it; the sensitive original stays encrypted.
  • Narrow the set with other conditions first, then decrypt and sort in the application: for example fetch a page by customer ID and creation time (not sensitive), then decrypt and sort. Only for small result sets.
  • Hand it to a separate search service: if you truly need full-text or fuzzy search (support finding someone by part of an address), build a search service with strictly controlled access that alone sees plaintext, rather than making the main database support fuzzy queries.

Arbitrary substrings (LIKE '%abc%'): there is no practical scheme that does not leak; use the search service above, or re-examine whether the requirement is real.

Deterministic encryption (AES-SIV) is an alternative to blind indexes for equality: the same plaintext with the same AAD always gives the same ciphertext, so you can query WHERE email_ct = $1 directly without an extra index column. A comparison:

AspectBlind index (HMAC) + random-nonce GCMDeterministic encryption (AES-SIV)
ColumnsTwo (ciphertext + index)One
LeakageEquality; can be reduced by truncationEquality; cannot be truncated
Same value in different rowsDifferent ciphertexts, only the index matchesSame ciphertext (unless the AAD has the row ID, which breaks lookups)
LibraryStandard library is enoughNot in Go's standard library; use something like Tink
FitsMost cases; truncation or several index kindsEquality only, one column fewer

This article chooses blind indexes because they can be truncated, one column can have several kinds of index (full, last four), and only the standard library is needed.

Some databases offer built-in "queryable encryption". MongoDB's Queryable Encryption, for example, has the client driver encrypt before sending, and the server can run equality queries on encrypted fields; which query types are supported depends on the version. If your data already lives in such a database it is worth evaluating; PostgreSQL has no equivalent official feature, so the approach in this article is what you use there.

Step 10: Key rotation and background re-encryption

Times to rotate: on a schedule (say yearly), when people leave, on suspected compromise, and at the encryption count limit mentioned in Step 3. Because each ciphertext records its key version, rotation can be done in stages without downtime:

① Add v2 every instance can decrypt v2 ② Writes use v2 Current becomes v2 v1 decrypts only ③ Re-encrypt batches of 500, SKIP LOCKED ④ Retire v1 confirm v1 rows = 0 remove from keyring ⑤ Destroy v1 after old backups expire, in the KMS rows still on v1 time → Rotating the blind index key is harder: old values can only be recomputed from plaintext. Add email_bidx_v2 → dual write → backfill by decrypting → switch queries → drop the old column. Create the unique index on the new column only after the backfill.

Figure: first make every instance know v2, then switch new writes to v2 and re-encrypt in background batches; remove v1 from the keyring only when no rows use it, and destroy it in the KMS only after old backups expire.

  1. Add v2, but keep Current at v1. Deployments roll, so every instance must be able to decrypt v2 before anyone writes v2; otherwise data written with v2 by a new instance cannot be read by an old one.
  2. Switch Current to v2. New data uses v2; v1 only decrypts.
  3. Re-encrypt in the background. ReencryptBatch (the code in Step 7) takes a batch of rows with an older key_version in one short transaction; FOR UPDATE SKIP LOCKED lets several workers run in parallel without blocking live writes; Reencrypt does nothing to values already on the new version, so rerunning after an interruption is safe. Pause between batches to avoid slowing the database, and track the remaining count with a metric.
  4. Retire v1. Only after SELECT count(*) FROM customers WHERE key_version < 2 returns zero, remove v1 from the Keyring.
  5. Destroy v1. Old backups still within their retention period were encrypted with v1; destroying v1 in the KMS destroys the personal data in those backups. Sometimes that is the point ("crypto-shredding" after backups expire), but make sure first that nobody still needs them.

Rotating only the master key (KEK) does not touch the data at all; you just re-wrap the DEKs with the new master key (Vault Transit's rewrap, or unwrap with the KMS and wrap again). Most "rotate regularly" requirements actually refer to this layer, and it is cheap.

Rotating the blind index key is much harder. HMAC cannot be converted: old index values cannot become index values under the new key; they can only be recomputed from plaintext, and during the rotation queries must find both old and new data. The approach is a column migration: add email_bidx_v2, dual write, backfill by decrypting in the background, switch queries to the new column, create the unique index once the backfill is complete (the CREATE INDEX CONCURRENTLY from “Adding Indexes Safely: Indexing Large Tables Without an Outage” applies), and finally drop the old column. So unless compromise is suspected, the blind index key is usually not rotated on a schedule.

Step 11: Going live and operating it

Migrating existing plaintext data to ciphertext. Like any column migration, do it in stages, each of which can be rolled back:

  1. Add nullable email_ct and email_bidx columns.
  2. Change the code to dual write: plaintext, plus ciphertext and blind index.
  3. Backfill old data in background batches.
  4. Read the ciphertext first, falling back to plaintext when it is NULL (dual read); check that both agree.
  5. Move the unique constraint to email_bidx and switch every query to the blind index.
  6. Stop writing plaintext, and finally drop the plaintext column.

Dropping a column does not make the data disappear. PostgreSQL's ALTER TABLE ... DROP COLUMN does not rewrite existing rows immediately; the old values stay in the data files until the table is rewritten (for example by VACUUM FULL); WAL archives, replicas and past backups still hold plaintext too. Plan around the backup retention period, and record "old backups contain plaintext" in the risk register.

No plaintext in logs or events. However good the encryption, one log.Info("customer", "email", email) undoes it. The previous article redacted by key name with slog's ReplaceAttr; this article adds another layer: decrypted values use the PII type, which implements slog.LogValuer and prints as [REDACTED]. Logs record the customer ID; anyone who needs the original value looks it up in an authorised back office. Events are the same: the events in “Message Queues and Event-Driven Design” are kept in JetStream for a while, so they carry only IDs, and consumers that need contact details call the order API.

Decrypt only in the service that owns the data. When payment needs to send a receipt, do not give it a copy of the DEK; it calls order for the fields it needs, or order sends the email. The fewer services hold the key, the smaller the "does not stop" cell in Step 1's diagram. This is also what the KMS IAM policy expresses: only order's service identity can unwrap this DEK.

Audit decryption. The KMS logs every DEK unwrap, but after startup the service no longer calls the KMS, so "who looked at which customer's national ID" must be recorded by the application: every time the support back office shows a full value, write an audit record (who, when, which customer, which column); normally show only masked values, and decrypt only when someone clicks "show full value".

Backup and restore. Sensitive columns in backups are ciphertext, but restoring requires the matching DEK versions to still exist. When you rehearse a restore, also verify "decrypt with the keys of that time"; plan key destruction together with backup retention.

Performance. Each value grows by 33 bytes; each blind index is 32 bytes, less when truncated. AES-GCM is fast on CPUs with hardware acceleration, and encrypting or decrypting one column usually costs far less than one database round trip; the real cost is that filtering and sorting can no longer happen in the database, so more data comes back to the application to be decrypted. If a list page only shows masked values, store a separate non-sensitive masked column (say, the last three digits of the phone) so the list needs no decryption. If performance is in doubt, measure it as in “Performance Tuning in Go: pprof and Benchmarks” rather than guessing.

Common pitfalls

  • Assuming disk encryption means the data is encrypted. Disk encryption is fully transparent to DBAs, SQL injection and pg_dump; it stops a different threat.
  • Repeated nonces. A fixed nonce, a timestamp as nonce, or a nonce pasted in as a constant; once a nonce repeats under one key, GCM loses both confidentiality and integrity.
  • No AAD. Ciphertexts can be swapped between rows, and someone with write access can make the system show them another person's email.
  • No row ID before encryption. If the database's sequence is part of the AAD you must INSERT and then UPDATE; use application-generated IDs.
  • SHA-256 as a blind index. Mobile numbers and national IDs have few possible values, so an unkeyed hash can be brute-forced and reversed; use HMAC, and protect its key like the encryption key.
  • Different normalisation on write and on query. Registration did not lowercase but lookup does: the unique constraint misses duplicate accounts, and users cannot log in.
  • Blind indexes on low-entropy columns. A blind index on gender, tier or birthday is almost plaintext.
  • A truncated index used for a unique constraint, or not re-checked after querying. Truncation always collides; decrypt the results to confirm.
  • OPE for sorting, or a pile of n-gram indexes for fuzzy search. Every extra query capability is extra leakage; first ask whether equality or a coarse column would meet the need.
  • Removing the old key before re-encryption finishes. The remaining data can never be decrypted; confirm that no rows use the old version before removing it.
  • pgcrypto with statement logging on. Keys and plaintext follow the SQL into logs and monitoring tools.
  • Encrypting card numbers and storing them yourself. That is still storing card numbers; let the payment provider tokenise them.
  • Assuming the data is gone once the plaintext column is dropped. Old row versions, WAL, replicas and old backups still have it.
  • Decrypted values in logs or events. Use a LogValuer type and the rule "events carry only IDs" to prevent it structurally.

Key takeaways

  • TLS, disk encryption and field encryption cover different ground; only field encryption stops DBAs, leaked backups, rows read by SQL injection and data copies. Use all three layers together.
  • Encrypt only columns that are truly sensitive and must be read back; do not store card numbers, let the payment provider tokenise them; know the difference between encryption, hashing, tokenisation and masking.
  • Default to AES-256-GCM: a random 12-byte nonce each time, at most 2^32 values per key, "table + column + row ID" as AAD so ciphertexts cannot be moved; no ECB, nothing home-made.
  • Envelope encryption: the master key stays in the KMS, data keys are stored wrapped, unwrapped at startup and cached; every ciphertext starts with its key version.
  • Built-in pgcrypto and AES_ENCRYPT() send keys and plaintext through the database; TDE and disk encryption do not stop anyone who can connect.
  • Use blind indexes for equality and unique constraints: HMAC-SHA256 over the normalised value, with a key separate from the encryption key and a domain mixed in.
  • Blind indexes leak equality and frequency; skip them on low-entropy columns, and for partial matches use truncated indexes and decrypt to re-check after querying.
  • Prefix search is possible with n-gram blind indexes at a higher leakage cost; avoid OPE/ORE for range and sort, and use coarse columns or a separate search service instead.
  • Rotation has five stages, and the old version is removed only when no rows use it; master key rotation is just re-wrapping, while blind index key rotation needs a column migration.
  • Migrate existing data with dual writes, backfill, dual reads and then dropping plaintext; keep plaintext out of logs and events; decrypt only in the owning service, and audit every view of a full value.

References

Next

Security in this series has now gone from authentication and authorisation between services all the way down to individual database columns. But every request passes through the outermost layer before it reaches any code. The next article, “Go Behind nginx: Security Settings and API Reverse Proxy Configuration”, covers the nginx in front of Go services: how to configure TLS, security headers, rate limiting, the reverse proxy and timeouts, and how the Go side should trust the headers the proxy passes on.