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.

published: reading time: 33 min read author: Geek Workbench updated: June 17, 2026
Quick Summary

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:

  1. Deterministic encryption: Equal plaintexts produce equal ciphertexts, which can support equality lookups but reveals repeated values and patterns

  2. Searchable encryption schemes: Specialized algorithms that allow searches without full decryption (research actively evolving)

  3. 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

1. Your TDE-encrypted database shows 30% higher CPU usage compared to before encryption. Is this expected and how do you reduce it?
Encryption overhead varies with the database, hardware, and workload, so compare representative measurements before and after enabling it. On Linux, look for the 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.
2. You need to rotate encryption keys for a 10TB database. How do you plan the migration without downtime?
Keep a version identifier with each encrypted value so the application can select the matching DEK. New writes can use a newly created DEK while a background job re-encrypts older records in batches. That avoids a single long outage, but the previous DEK must remain available until all records and backups that depend on it have expired or been migrated. Estimate migration time from a measured throughput test, then use throttling, checkpoints, and rollback planning to protect the live workload.
3. What is the difference between TDE and column-level encryption, and when would you choose each?
TDE encrypts supported database storage and usually needs little application change. It protects stored files when the database key is unavailable, but the running database still serves plaintext to authorized queries. Application-level encryption protects selected fields before they reach the database, which can keep those fields unreadable to database operators, at the cost of added key handling and reduced searchability. Choose based on the threat boundary you need and test backup and restore behavior for either option.
4. Your KMS is throttling 20% of write operations due to key access limits. How do you fix this?
Check the current quota and throttling metrics for the KMS key and region instead of assuming one fixed request limit. Envelope encryption reduces KMS calls: use a data key locally for a bounded set of operations, store its encrypted copy with the ciphertext, and set a cache lifetime that matches your risk requirements. If the workload still exceeds its target, profile the calls and evaluate batching through a supported client-side encryption library. Do not share plaintext DEKs through a cache unless its access controls, lifetime, and failure behavior have been reviewed.
5. An auditor asks you to prove that encryption keys were not compromised in the last 90 days. How do you provide evidence?
Logs can show recorded key operations and help identify unusual activity, but they cannot prove that a key was never exposed or used through an unobserved path. Preserve access-controlled KMS or Vault audit records, review principals, source context, decrypt activity, and policy changes, and document the limits of that review. Pair the evidence with access reviews, incident records, and key-management controls. Describe the conclusion as an assessment of available evidence, not proof of no compromise.
6. You discover that a former employee had access to encryption keys and left 6 months ago. What do you do?
Revoke any remaining identity, token, and role access, then preserve key-service audit records and review which operations the account could perform. If exposure is plausible, follow the incident process to assess affected data and decide whether to rotate or replace keys; rotating a KEK alone does not repair a compromised DEK. Involve privacy and legal owners to determine any notification duties from the facts and applicable rules. Update offboarding controls so key access is removed with other credentials.
7. How does encryption at rest protect against a physical storage theft scenario, and what are its limitations?
TDE can protect a copied drive or database file when the copy does not include usable keys. It does not hide query results from the running database, protect plaintext in memory, or stop an authorized account from reading data. Treat it as storage protection and keep logical access controls, backup encryption, and key permissions in scope.
8. What is envelope encryption and why is it the recommended approach for large-scale encryption at rest deployments?
Envelope encryption uses a data encryption key (DEK) for the data and a key encryption key (KEK) to protect the DEK. Rewrapping DEKs under a new KEK can avoid rewriting the data when only the KEK changes. If a DEK itself is exposed, rewrapping does not fix the exposure; affected data needs a new DEK and re-encryption. Store the wrapped DEK and version metadata with the ciphertext, while keeping the KEK in the key service.
9. Your security team requires a FIPS-validated cryptographic module. How does this affect your implementation choices?
Confirm the exact standard and validation requirements that apply. FIPS 140-3 covers cryptographic module security, so selecting AES alone does not establish compliance. Check the validated module, version, operating mode, and approved configuration for the system you plan to deploy. Have the compliance owner confirm how those requirements apply to your service and its full data path.
10. How do you handle encryption key rotation in a zero-downtime environment where data must remain accessible?
Keep both key versions available during migration. Write new data with the new key, and let a checkpointed background job decrypt old records with the old DEK and write them with the new one. Reads must handle either version until the migration is complete. Verify record counts and application-level integrity before retiring the old DEK, and retain any keys still needed by backups. Test rollback and failure recovery before doing this on production data.
11. Your application uses column-level encryption and the team debates whether the encryption key should live in the application or the database. What are the trade-offs?
If encryption runs in the application, the database can store ciphertext without receiving the application's plaintext key, but application operators and runtime access remain in the trust boundary. With database-side functions such as 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.
12. A regulatory requirement mandates encryption at rest for all "sensitive personal data." How do you classify what requires encryption?
Classify data with the rules that apply to your organization and the exposure you are trying to prevent. A user table may mix account numbers, contact details, and public profile fields, so record the protection decision at field or data-set level. Map each category to safeguards, key ownership, and review cadence; confirm legal or contractual requirements with the responsible compliance owner. Encryption scope should follow that analysis rather than a universal label or key-per-record rule.
13. How does confidential computing change the threat model for encryption at rest?
Confidential computing can protect a workload's memory from some privileged host software by using hardware-backed isolation. Data is still available in plaintext inside the trusted execution environment while it is processed, and the approach depends on the hardware, attestation, workload design, and provider configuration. It complements encryption at rest; it does not replace transport encryption, application authorization, or careful key release policies.
14. Your company is migrating from on-premises databases to a cloud provider. How do you maintain encryption key control?
BYOK typically means generating key material under your process and importing it into the provider's key service; once imported, the service performs operations under its own controls. It does not automatically mean the provider cannot use the key. HYOK keeps key operations in infrastructure you control, which can add network, availability, and integration constraints. Confirm what "control" means in the requirement, then test the key service's access model and outage behavior before choosing either approach.
15. What is the difference between envelope encryption and direct encryption, and when would you choose each?
In envelope encryption, store ciphertext with the DEK's wrapped copy and version metadata; keep the KEK in KMS or an HSM. Rewrapping the DEK under a replacement KEK can avoid bulk data re-encryption when only the KEK changes. Direct encryption uses one key for the data itself and requires a secure way to retain and rotate that key. Envelope encryption helps when you need separate data keys or need to change the wrapping key without rewriting large datasets.
16. How do you handle encryption for database backups that go to third-party storage (S3, Azure Blob)?
Choose a backup encryption boundary that matches your threat model and recovery plan. Provider-managed encryption is operationally simple, while client-side encryption can separate key access from the storage account. That separation does not guarantee protection if the same compromised environment can obtain the key or request decryption. Keep required key versions available for the retention period, restrict restore roles, test recovery, and confirm deletion when backup retention ends.
17. Your organization uses multi-tenant database architecture. How do you design key management to ensure tenant isolation?
For cryptographic tenant separation, use distinct data keys or another explicit cryptographic boundary per tenant, and protect each data key with an appropriately scoped key-encryption key. Store the wrapped key and version with the ciphertext, and restrict which application identity can unwrap it. TDE alone generally protects the database storage boundary, not individual tenants. Per-tenant keys can reduce the impact of a single key exposure, but authorization checks and careful tenant-to-key mapping remain necessary.
18. A penetration tester demonstrates that your TDE-encrypted database can be read by connecting to the running instance. What is the vulnerability?
This is expected TDE behavior. The database decrypts data for queries, so a user with database access can read whatever that account is authorized to read. TDE protects storage copies; application-layer encryption can keep selected fields unreadable to database users if the application retains the keys separately. Restrict database roles to the data each service needs.
19. How do you design encryption key expiration and renewal without breaking existing encrypted data?
Key expiration design: embed a key version identifier in the ciphertext (e.g., 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.
20. Your audit reveals that encryption keys are stored in environment variables on application servers. How do you remediate this?
Treat the key as exposed until you have assessed its use and replaced it. Restrict the application identity, move key handling to an approved key service, and review logs and access policies for unexpected use. Remove the value from active configuration and source history where possible; if it was committed or otherwise exposed, rotation alone is not enough unless encrypted data and backups can still be recovered. Use a bounded cache only when the design accounts for revocation and recovery.

Further reading


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.

#database #audit #compliance

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.

#database #data-masking #security

GDPR Engineering Patterns for Database Systems

Engineering patterns for GDPR data requests, backups, consent, processors, and breach response, with legal scope and implementation limits.

#database #gdpr #compliance