Encryption at Rest: TDE, Key Management, and Performance
Compare storage encryption, database TDE, and application encryption. Review threat boundaries, key management, and a practical performance benchmark plan.
Encryption at rest protects stored bytes only within a defined key boundary. This guide compares TDE with field-level encryption, explains envelope keys and rotation, and shows where KMS or Vault fit. Use it to choose controls for your threat model, benchmark their costs, and rehearse key recovery before depending on them.
Encryption at rest: TDE, key management, and performance
Introduction
If a disk or backup leaves your control, encryption can keep its contents unreadable to whoever gets the copy. The protection depends on where decryption happens and who can access the key.
This guide covers Transparent Data Encryption at the database level, application-layer encryption for sensitive fields, key management infrastructure, and the performance realities you need to understand before deploying to production.
flowchart LR
subgraph KEK["Key Hierarchy"]
MK[("Master Key<br/>KMS/HSM")]
end
subgraph DEK["Data Key Layer"]
DK1[("DEK v1<br/>User Data")]
DK2[("DEK v2<br/>User Data")]
DK3[("DEK<br/>Config Data")]
end
subgraph Storage["Storage Layer"]
E1[("Encrypted<br/>User Table")]
E2[("Encrypted<br/>Config Table")]
E3[("Encrypted<br/>Backup")]
end
MK -->|encrypts| DK1
MK -->|encrypts| DK2
MK -->|encrypts| DK3
DK1 -->|encrypts| E1
DK2 -->|encrypts| E2
DK3 -->|encrypts| E3
E1 -.->|rotate| DK2
Transparent data encryption (TDE)
TDE encrypts data at the storage level, between the database and disk. The database engine handles encryption and decryption transparently: applications continue working without modification.
Keep three controls distinct. Disk or volume encryption protects a storage device or volume if it is detached or copied without its key; it does not encrypt selected fields. Database TDE encrypts database-managed files and logs while the engine transparently serves plaintext to authorized queries. Application or column encryption encrypts selected values before they reach the database, which can hide them from database-only users when the application key is kept outside the database. The application and its runtime remain trusted.
PostgreSQL field encryption with pgcrypto
pgcrypto can encrypt selected values when a query calls an encryption
function. It is not transparent data encryption (TDE), and the database
process receives the plaintext and key material, so the database remains in
the trust boundary. PostgreSQL documents pgcrypto as a set of cryptographic
functions, not storage encryption. Its raw encrypt() / decrypt() functions
do not provide integrity checks; do not treat them as authenticated
encryption. See the PostgreSQL pgcrypto documentation.
-- Enable pgcrypto
CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- Store encrypted values in bytea columns.
CREATE TABLE customer_data (
id SERIAL PRIMARY KEY,
name TEXT,
ssn_encrypted BYTEA,
credit_card_encrypted BYTEA
);
-- Demo only: use a non-production passphrase; psql \prompt is not a secure
-- secret-input channel.
\prompt 'Demo passphrase (not for production): ' encryption_passphrase
INSERT INTO customer_data (name, ssn_encrypted, credit_card_encrypted)
VALUES (
'Jane Smith',
pgp_sym_encrypt('example-ssn', :'encryption_passphrase'),
pgp_sym_encrypt('example-card-number', :'encryption_passphrase')
);
This example keeps secrets out of the schema, but a production design still needs managed keys, protected connections, and a tested recovery path.
MySQL InnoDB data-at-rest encryption
MySQL InnoDB can encrypt supported tablespaces when a keyring component or plugin is installed and configured at server startup. Centralized key management options depend on the edition and deployment.
-- The keyring must already be configured and available to InnoDB.
CREATE TABLE sensitive_data (
id INT PRIMARY KEY,
data VARCHAR(255)
) ENCRYPTION='Y';
Microsoft SQL Server TDE
SQL Server TDE encrypts entire databases:
-- Create master key
-- Supply a strong deployment-specific secret through your approved setup.
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'replace-with-managed-secret';
-- Create certificate
CREATE CERTIFICATE MyServerCert WITH SUBJECT = 'TDE Certificate';
-- Create database encryption key
USE mydatabase;
CREATE DATABASE ENCRYPTION KEY
WITH ALGORITHM = AES_256
ENCRYPTION BY SERVER CERTIFICATE MyServerCert;
-- Enable encryption
ALTER DATABASE mydatabase SET ENCRYPTION ON;
TDE limitations
TDE encrypts database-managed storage while the database is stopped or the storage is copied without its key. When the database is running, the engine decrypts pages for authorized work, so TDE does not protect query results from a compromised account or privileged operator. Whether exports and backups receive the same protection depends on the database and backup configuration; verify that boundary separately.
Key granularity depends on the implementation. Many TDE systems use a database or tablespace key hierarchy rather than a separate key for each row. That protects the storage boundary but does not create cryptographic isolation between tenants. Check how the database scopes and rotates its keys.
Memory exposure. A running database decrypts pages for queries. SQL injection, a compromised service account, or a privileged operator can read data allowed by that account’s permissions. TDE does not replace database access controls.
Access control still applies. TDE does not change who can read data. Database access controls, application permissions, and row-level security policies still determine what users can see. An attacker who has obtained database credentials has already bypassed TDE entirely, regardless of how strong your encryption is.
Backup encryption is often separate. Many TDE implementations do not automatically encrypt backups. An export may be unencrypted even when the live database files use TDE. Verify in your runbook how each backup path is encrypted and where its keys are stored.
Application-level encryption
For sensitive fields such as PII, credentials, or financial data, application-layer encryption gives you finer-grained control. Encrypt selected values before sending them to the database.
Column-level encryption example
from cryptography.fernet import Fernet
class FieldEncryptor:
def __init__(self, fernet_key: bytes):
# Inject a URL-safe base64-encoded key from a key manager.
self.fernet = Fernet(fernet_key)
def encrypt(self, plaintext: str) -> str:
"""Returns a URL-safe encoded authenticated ciphertext."""
return self.fernet.encrypt(plaintext.encode()).decode()
def decrypt(self, ciphertext: str) -> str:
"""Decrypts a Fernet token."""
return self.fernet.decrypt(ciphertext.encode()).decode()
# Supply a data key from a managed key service; do not hardcode it here.
# `fernet_key_from_key_manager` is a URL-safe base64-encoded 32-byte key.
encryptor = FieldEncryptor(fernet_key_from_key_manager)
# Encrypt before storing
email = 'user@example.com'
encrypted_email = encryptor.encrypt(email)
# Store encrypted_email in database
# Decrypt when reading
decrypted_email = encryptor.decrypt(encrypted_email)
Searchable encryption
A challenge with application-layer encryption: how do you search encrypted data? Options include:
-
Deterministic encryption: Equal plaintexts produce equal ciphertexts, which can support equality lookups but reveals repeated values and patterns
-
Searchable encryption schemes: Specialized algorithms that allow searches without full decryption (research actively evolving)
-
Search index separate from data: Maintain an unencrypted index mapping search terms to encrypted record IDs (requires careful access control)
-- Pattern-matching on encrypted data is impossible
-- You need application-level search
CREATE INDEX idx_email_hash ON users(email_hash);
Encryption in transit vs. at rest
These three protections guard different surfaces, and mixing them up is one of the most common ways security designs end up with gaps you do not notice until something goes wrong.
Encryption in transit guards data moving between two endpoints. The threat is network interception: a wire tap, a man-in-the-middle, a compromised router. TLS 1.2+ with strong cipher suites handles this. mTLS goes further by authenticating both sides, which matters inside network perimeters where you are not the only tenant. Without TLS, anything crossing a wire is exposed. Internal network traffic is not automatically safe either: internal networks get compromised, and lateral movement is how attackers actually operate once they are inside.
Encryption at rest protects data stored on disks, in backups, and in cold archives. It can help when someone gets a storage copy without the key. TDE handles this at the storage layer; application encryption can protect selected fields. Both leave data available in plaintext to the running database or application, so they do not address an attacker with access to those processes.
Encryption in use aims to protect data while the CPU processes it. A hypervisor compromise, OS-level exploit, or privileged insider may otherwise read process memory. Confidential computing technologies such as Intel SGX, AMD SEV, or AWS Nitro Enclaves use hardware-backed isolation, but data is still plaintext inside the trusted environment. The approach adds performance and API costs, so use it when the threat model calls for that isolation.
Most systems need to consider all three, but the required controls depend on the threat model. Encryption at rest protects stored copies; TLS protects data moving between endpoints; confidential computing can isolate some data while it is processed. Choose each control for the exposure it addresses.
| Protection | What it guards | Implementation |
|---|---|---|
| Encryption in transit | Data moving over network | TLS/SSL, mTLS |
| Encryption at rest | Data stored on disk | TDE, application-layer |
| Encryption in use | Data in memory | Confidential computing (emerging) |
Key management
Key management determines who can use or recover encrypted data. Hardcoded keys, overdue rotation, or broad decrypt permissions can undo much of the protection encryption provides.
AWS KMS integration
AWS Key Management Service provides centralized key storage and management:
import boto3
import base64
from cryptography.fernet import Fernet
def encrypt_with_kms(aws_region: str, key_id: str, plaintext: str) -> dict:
kms = boto3.client('kms', region_name=aws_region)
encryption_context = {'purpose': 'example-field-encryption'}
# Generate data key from KMS
response = kms.generate_data_key(
KeyId=key_id,
KeySpec='AES_256',
EncryptionContext=encryption_context,
)
# Encrypt plaintext with data key
data_key = response['Plaintext']
encrypted_data_key = response['CiphertextBlob']
fernet = Fernet(base64.urlsafe_b64encode(data_key))
encrypted_plaintext = fernet.encrypt(plaintext.encode())
del data_key
return {
'encrypted_data_key': base64.b64encode(encrypted_data_key).decode(),
'ciphertext': base64.b64encode(encrypted_plaintext).decode(),
'encryption_context': encryption_context,
}
def decrypt_with_kms(aws_region: str, encrypted_blob: dict) -> str:
kms = boto3.client('kms', region_name=aws_region)
# Decrypt the data key
encrypted_data_key = base64.b64decode(encrypted_blob['encrypted_data_key'])
response = kms.decrypt(
CiphertextBlob=encrypted_data_key,
EncryptionContext=encrypted_blob['encryption_context'],
)
data_key = response['Plaintext']
# Decrypt the data
ciphertext = base64.b64decode(encrypted_blob['ciphertext'])
fernet = Fernet(base64.urlsafe_b64encode(data_key))
plaintext = fernet.decrypt(ciphertext).decode()
del data_key
return plaintext
The example uses a fixed, non-sensitive encryption context so the decrypt request can supply the same values. In production, store the context needed for decryption with the ciphertext, and never put secrets or personal data in it because KMS audit logs include it.
KMS best practices:
- Use a customer-managed KMS key when you need direct control over its policy; provider-managed keys may be enough when their defaults meet your needs.
- Implement key rotation (automatic or manual)
- Use key policies and IAM for access control
- Enable and audit CloudTrail logging for key usage
HashiCorp Vault for key management
Vault provides a comprehensive secrets management solution:
# Enable transit secrets engine for encryption as a service
vault secrets enable transit
# Create an encryption key
vault write -f transit/keys/myapp-key
# Encrypt data via Vault API
vault write transit/encrypt/myapp-key \
plaintext=$(echo -n "sensitive data" | base64)
# Decrypt via Vault API
vault write transit/decrypt/myapp-key \
ciphertext="vault:v1:..."
# Rotate the key (new version available, old preserved)
vault write -f transit/keys/myapp-key/rotate
import hvac
def encrypt_with_vault(vault_url: str, token: str, key: str, plaintext: str) -> str:
client = hvac.Client(url=vault_url, token=token)
response = client.secrets.transit.encrypt_data(
name=key,
plaintext=plaintext
)
return response['data']['ciphertext']
def decrypt_with_vault(vault_url: str, token: str, key: str, ciphertext: str) -> str:
client = hvac.Client(url=vault_url, token=token)
response = client.secrets.transit.decrypt_data(
name=key,
ciphertext=ciphertext
)
return response['data']['plaintext']
Vault advantages over KMS:
- Single control plane for all secrets (keys, passwords, certificates)
- Fine-grained access policies
- Audit logging of all secret access
- Dynamic secrets (on-demand credentials)
- Encryption as a service (no key material leaves Vault)
Key rotation strategy
Scheduled key rotation can limit how much data depends on one key version, but it does not undo exposure if a key was compromised. Assess whether affected ciphertext needs a new DEK and re-encryption.
import base64
from cryptography.fernet import Fernet
class KeyRotator:
def __init__(self, kms_client, wrapped_deks: dict[int, tuple[bytes, dict[str, str]]]):
self.kms = kms_client
# Each stored version includes the base64 encrypted_data_key and its
# exact encryption_context; decode the blob when loading. In memory,
# each entry is (CiphertextBlob, EncryptionContext).
self.wrapped_deks = wrapped_deks
self._key_cache = {}
def get_dek(self, key_version: int) -> bytes:
"""Get data encryption key for specific version"""
if key_version in self._key_cache:
return self._key_cache[key_version]
encrypted_dek, encryption_context = self.wrapped_deks[key_version]
response = self.kms.decrypt(
CiphertextBlob=encrypted_dek,
EncryptionContext=encryption_context,
)
self._key_cache[key_version] = response['Plaintext']
return self._key_cache[key_version]
def rotate_and_reencrypt(self, old_version: int, new_version: int, records: list) -> list:
"""Re-encrypt records with new key version"""
old_key = self.get_dek(old_version)
new_key = self.get_dek(new_version)
result = []
for record in records:
# Decrypt with old key
fer_old = Fernet(base64.urlsafe_b64encode(old_key))
plaintext = fer_old.decrypt(record['encrypted_data'])
# Encrypt with new key
fer_new = Fernet(base64.urlsafe_b64encode(new_key))
result.append({
**record,
'encrypted_data': fer_new.encrypt(plaintext),
'key_version': new_version
})
return result
Performance overhead
Encryption has measurable costs. Understanding them helps you design appropriately.
Estimating TDE performance impact
There is no reliable overhead percentage that applies across database engines and workloads. Use a representative benchmark before estimating capacity.
Reads can reuse pages held in the buffer pool, while writes add encryption work as dirty pages are flushed. Bulk loads may make that work more visible because they produce many dirty pages quickly. At 200 MB/s with 16 KB pages, the system flushes about 12,800 pages per second; actual CPU cost depends on the database and encryption implementation.
The latency impact depends on the workload. If encryption adds 0.5 ms to a 10 ms operation, the relative change is small; the same delay matters more for a latency-sensitive service. Measure read and write latency separately, then load-test bulk operations and compare results with your service objectives.
Hardware without accelerated AES can pay a higher CPU cost, but there is no reliable multiplier across database engines and instance types. Benchmark the actual deployment rather than extrapolating from a processor label.
Use these workload descriptions to plan measurements. Database engine, hardware, storage, and workload can produce different results.
| Workload | Measure before and after enabling TDE |
|---|---|
| Read-heavy | Throughput, CPU, and read latency |
| Mixed | Throughput, CPU, and read/write latency |
| Write-heavy | CPU, write latency, and queue depth |
| Bulk load | Completion time and storage throughput |
Mitigating performance impact
Potential mitigations depend on where the measured bottleneck occurs.
Hardware acceleration can reduce the CPU cost of AES, but the result depends on the processor, database engine, storage, and workload. On Linux, check for the aes CPU flag in /proc/cpuinfo or inspect the provider’s instance documentation. Benchmark your own read, write, and bulk-load patterns before estimating production overhead.
Key caching can reduce remote key-service calls. A request to KMS or Vault adds network and service latency, so calling it for every row can make it part of the write path. Envelope encryption lets the application use a DEK locally for a bounded set of operations and store the wrapped copy with the ciphertext. Set a cache lifetime based on your exposure and revocation needs; there is no universal safe TTL. The KEK stays in the key service while the application handles the plaintext DEK only for as long as necessary.
Encrypt only what matters can keep extra work focused on fields that need a separate boundary, such as account numbers or credentials. TDE covers supported database storage, while column-level encryption adds work when the application reads or writes protected values. Neither approach has a fixed performance cost across schemas. Benchmark the actual workload and avoid encrypting fields without a clear security or policy reason.
Batch operations amortize key access overhead across many records. How you structure the calls matters more than which algorithm you pick:
import base64
from cryptography.fernet import Fernet
# Avoid: one KMS data-key request per record
for record in records:
data_key_response = kms.generate_data_key(KeyId=key_id, KeySpec='AES_256')
# Encrypt the record with data_key_response['Plaintext'].
# Better: one data key for a bounded batch
response = kms.generate_data_key(KeyId=key_id, KeySpec='AES_256')
dek = response['Plaintext']
wrapped_dek = response['CiphertextBlob'] # Store with the encrypted batch.
fernet = Fernet(base64.urlsafe_b64encode(dek))
for record in records:
encrypted = fernet.encrypt(record['ssn'].encode()) # ~1μs per value
del dek
At 100K records, per-row KMS calls take 10-50 seconds. Batch with a cached DEK takes under a second.
Asynchronous processing can move encryption work off a latency-sensitive path when delayed availability is acceptable. If the queue persists messages or writes them to disk, encrypt sensitive values before they enter the queue; otherwise plaintext may be exposed in queue storage, replicas, or backups. This approach adds operational complexity and does not fit transactions that require immediate encrypted reads.
When to use / when not to use TDE vs application-level encryption
Use TDE when:
- You need baseline protection against physical media theft
- Compliance requires encryption at rest without application changes
- You want minimal operational overhead
Do not use TDE alone when:
- You need column-level access control (TDE decrypts everything for privileged users)
- You need to encrypt only specific fields (use application-layer)
- Regulatory requirements mandate key-per-tenant isolation
Use Application-Level Encryption when:
- You need field-level encryption with separate keys per user or tenant
- Privileged users (DBAs) must not see sensitive data
- You need searchable encrypted data (deterministic encryption)
- Compliance requires key custody separate from data storage
Do not use Application-Level Encryption when:
- Performance overhead is unacceptable and TDE suffices
- Your team lacks secure key management expertise
Trade-off table
| Dimension | TDE (Database-Level) | App-Level Column Encryption | TDE + App-Level Combined |
|---|---|---|---|
| Coverage | Entire database | Selected columns only | Entire DB + sensitive columns |
| Privileged user access | Database query returns plaintext | Database-only users can lack the decryption key | Depends on who can call the application |
| Performance overhead | Measure for the database and workload | Measure for encrypted fields and traffic | Measure both layers together |
| Key management complexity | Low: DB manages | High: app must manage | Highest: dual key systems |
| Implementation effort | Low | High | Highest |
| Compliance scope | Media theft protection | Access control on data | Defense in depth |
| Key strategy | Benefit | Cost or risk | Good fit |
|---|---|---|---|
| Provider-managed key | Simple setup and fewer key operations for the team | Less control over policy and separation of duties | Baseline encryption where provider defaults meet policy |
| Customer-managed KEK with envelope encryption | KMS/HSM protects DEKs while data is encrypted locally; KEKs can often rotate by rewrapping DEKs | Requires key policies, version tracking, and a tested decrypt path | Large datasets or applications that need an auditable key boundary |
| Separate backup key or account | Limits the effect of production credential exposure | Recovery depends on retaining the backup key and its access path | Long-retention, cross-account, or isolated recovery copies |
Choose TDE when the main concern is lost media and the database manages encryption reliably. Add application-level encryption when database operators must not read selected fields or when tenants need separate cryptographic boundaries. Envelope encryption keeps bulk data away from the KMS API: the DEK encrypts the data and the KEK wraps the DEK. Keep backup key access recoverable but separate from ordinary production access, and test the full restore path before relying on it.
Production failure scenarios
| Failure | Impact | Mitigation |
|---|---|---|
| Key rotation breaking encrypted data | Data permanently unreadable | Test rotation thoroughly, maintain key version history |
| KMS throttling during high write load | Write latency spikes or failures | Cache DEKs locally, implement retry with backoff |
| Backup encryption without key export | Cannot restore to different account | Export key material with backups, test cross-account restore |
| Hardcoded encryption keys in code | Key exposure in version control | Use KMS/Vault exclusively, scan code for secrets |
| TDE without key rotation | Compromised key grants perpetual access | Implement automatic rotation schedule |
Capacity estimation: encryption overhead on I/O throughput
Encryption at rest adds CPU overhead to every read and write operation. The impact depends on the encryption layer and workload characteristics.
TDE (storage-layer) overhead formula:
effective_throughput = raw_throughput × (1 - encryption_overhead_ratio)
encryption_overhead_ratio = measured fraction for this workload
Use the formula to estimate effective throughput from a measured overhead ratio. Hardware acceleration can change the result, so measure both CPU and storage limits on the target system.
Application-level encryption estimate: Measure encrypt and decrypt latency for the actual field sizes and library, including serialization and key lookup. Then replay a representative read/write mix and record CPU, throughput, and tail latency. Do not convert a per-value microbenchmark into a production core estimate without measuring concurrency and batching.
Key rotation overhead: Re-encrypting data with a new key requires reading all encrypted data, decrypting with old key, re-encrypting with new key, and writing back. For 1TB of encrypted data with 10MB/s re-encryption throughput: 1TB / 10MB/s = 100,000 seconds ≈ 27 hours. Plan key rotation during maintenance windows or use key versioning (encrypt new data with new key, decrypt old data lazily on read) to avoid bulk re-encryption.
Observability checklist
Key metrics: KMS API call latency, KMS throttling events, key rotation timestamps, and encryption operation latency.
-- PostgreSQL with pgcrypto: monitor encryption function call latency
SELECT
query,
calls,
total_exec_time_ms,
mean_exec_time_ms,
max_exec_time_ms
FROM pg_stat_statements
WHERE query LIKE '%pgp_sym_encrypt%'
OR query LIKE '%pgp_sym_decrypt%'
ORDER BY total_exec_time_ms DESC;
# Alert: KMS API latency spike (could indicate KMS throttling)
- alert: KmsApiLatencyHigh
expr: histogram_quantile(0.95, kms_api_latency_seconds) > 0.5
for: 5m
labels:
severity: warning
annotations:
summary: "KMS API P95 latency {{ $value }}s exceeds 500ms"
# Alert: KMS throttling events
- alert: KmsThrottlingEvents
expr: rate(kms_throttling_total[5m]) > 10
for: 5m
labels:
severity: warning
annotations:
summary: "KMS throttling events rate: {{ $value }}/s"
# Critical: Encryption key approaching expiration
- alert: EncryptionKeyExpiring
expr: (key_expiration_timestamp - now()) < 2592000 # 30 days
for: 1h
labels:
severity: critical
annotations:
summary: "Encryption key {{ $labels.key_id }} expires in {{ $value }} seconds"
# Alert: Encrypted volume showing high CPU during encryption operations
- alert: EncryptionCpuOverhead
expr: instance:cpu_encryption_overhead_percent > 15
for: 10m
labels:
severity: warning
annotations:
summary: "Encryption overhead consuming {{ $value }}% CPU on {{ $labels.instance }}"
Track key access and recovery as well as encryption performance:
- Alert on sustained KMS p95 latency above the service target, throttling, and failed encrypt or decrypt requests.
- Review decrypt, data-key generation, key-policy changes, disablement, and scheduled deletion by principal and region; alert on unexpected callers or locations.
- Track key age, scheduled rotation, DEK rewrap progress, and the remaining records encrypted with old DEKs.
- Monitor data-key cache misses, age, and refresh failures so performance tuning does not create an unbounded key lifetime.
- Report backup encryption coverage and run restore exercises that confirm the required key, role, and region are available.
- Compare storage, replica, backup, and key locations with the organization’s approved residency scope.
Alert thresholds should reflect normal traffic and the recovery objective. A successful KMS API call does not prove that the application used the right key version or that a retained backup can be restored.
Quick recap checklist
Use this checklist when designing or reviewing encryption at rest for a database system:
- Storage encryption enabled for production data where policy and threat analysis require it
- Sensitive fields use column-level encryption where required
- Encryption keys stored in KMS/Vault, not in application code
- Key rotation schedule set to match the key type, usage, risk, and applicable policy
- Backup encryption implemented with keys separate from production
- Hardware encryption support and production overhead benchmarked
- KMS throttling handled via DEK caching
- CloudTrail/Vault audit logs enabled and reviewed
- Encryption overhead benchmarked under realistic write load
- Key access termination procedure documented and tested
Security and compliance notes
Encryption requirements depend on the data, jurisdiction, and control framework. Some rules require protection for particular stored data; others call for a risk-based decision and documented safeguards. Do not treat the examples below as a complete legal checklist:
- Payment-card rules specify protections for stored account data.
- Health and privacy requirements can make encryption an appropriate safeguard, but obligations depend on the organization and the data involved.
- Audit frameworks commonly assess whether encryption controls are designed, implemented, and supported by evidence.
Document the encryption boundary and the decisions behind it:
- What data is encrypted (and where)
- Encryption algorithms and key lengths
- Key management procedures
- Access controls for key material
- Rotation schedules and procedures
Encryption settings do not establish data residency by themselves. Map where primary data, replicas, snapshots, logs, wrapped DEKs, and recovery copies are stored or processed. Confirm that the key service, backup destination, and restore role meet the organization’s location and access requirements; a key in one region does not prevent ciphertext or plaintext from moving elsewhere.
Keep key-use and policy-change evidence in access-controlled audit storage, and avoid logging plaintext, raw key material, or full sensitive records. Requirements for encryption, key custody, retention, and cross-border transfer depend on the data and jurisdiction, so confirm the applicable controls with privacy, legal, and compliance owners.
Common pitfalls / anti-patterns
- Rotating the KEK and assuming a compromised DEK is safe. Rewrapping changes the KEK protecting a DEK; it does not replace an exposed DEK. Re-encrypt affected data with a new DEK when the data key may be compromised.
- Keeping one DEK indefinitely for convenience. A long-lived or broadly shared data key increases blast radius. Scope keys to a sensible data boundary, track versions, and set a refresh or rotation policy.
- Caching data keys without an expiry. Caching reduces KMS calls, but an unbounded cache defeats revocation and increases exposure after process compromise. Bound cache lifetime and test refresh failures.
- Encrypting production backups but not proving restore access. A backup that depends on a deleted key, missing role, or inaccessible region is not recoverable. Keep required key versions available for the backup retention period and rehearse restoration.
- Treating an in-region key as proof of data residency. Check replicas, snapshots, logs, and restore destinations too; encryption does not control where a copy is stored.
- Giving application and backup operators the same broad key permissions. Separate duties where practical, grant only required key actions, and alert on unusual decrypt or policy-change activity.
Interview questions
aes CPU flag in /proc/cpuinfo or check the provider's instance documentation. If CPU rises sharply, profile database and storage activity, confirm the configured encryption path, and test changes against the same workload. Hardware upgrades may help, but do not assume encryption is the only cause.
pgcrypto, the database process receives the passphrase or key for the operation. TDE is different again: it encrypts storage transparently and does not hide query results from database users. Choose the boundary that fits your threat model, then test what each operator and service can actually decrypt.
v2:base64:...). On read, parse the version, use the corresponding key to decrypt. This allows multiple key versions to coexist during rotation. For renewal: add new key version, update application to use new key for new writes, re-encrypt old data in background (lazy or batch), deprecate old key only when all data is re-encrypted. Key version metadata can be stored in the first bytes of the ciphertext, a database column, or a key registry. Without versioning, key rotation breaks existing ciphertext.
Further reading
- Cloud Security: Broader security patterns
- Database monitoring: Signals for database health and key-service dependencies
- Compliance Automation: Maintaining security posture
- Threat modeling basics: Identify which storage threats need encryption controls
- PostgreSQL pgcrypto documentation: supported database encryption functions and their limits
- MySQL InnoDB data-at-rest encryption: keyring setup and tablespace encryption requirements
- AWS KMS data keys: envelope encryption and handling plaintext data keys
- NIST FIPS 140-3: security requirements for cryptographic modules
Conclusion
Encryption at rest protects stored bytes only within a defined key boundary. Choose TDE or field encryption based on who must be unable to read the data, keep wrapped keys and version metadata recoverable, and test rotation and restore paths before an incident forces the issue.
Category
Related Posts
PostgreSQL Audit Logging: Triggers, CDC, and pgAudit
Compare PostgreSQL triggers, logical decoding, and pgAudit for tracking order updates, including event fields, rollback behavior, ordering, and capture limits.
Data Masking Strategies for Non-Production Environments
Learn static and dynamic data masking: nulling, shuffling, hashing, and range techniques. Understand GDPR and PII considerations for PostgreSQL and Oracle.
GDPR Engineering Patterns for Database Systems
Engineering patterns for GDPR data requests, backups, consent, processors, and breach response, with legal scope and implementation limits.