Sub topic 14
Request quotas, cost and S3 Bucket Keys
This chapter assumes you have read the earlier chapters on direct Encrypt and Decrypt calls, envelope encryption, and key policies. You should know that every KMS API call is a billable, rate-limited request, and that an AWS service using your key makes those calls on your behalf.
Why request volume matters
KMS charges for keys and for requests, and it limits how many requests you can send per second. A design that calls KMS once per object or once per message is correct, but it can become expensive or hit a rate limit at high volume. Both problems come from the same cause: too many KMS calls. The fixes are the same too: make fewer calls.
What KMS costs
The figures below are US list prices at the time of writing. Check the AWS KMS pricing page for your Region before you plan a budget.
| Item | Typical price |
|---|---|
| Customer managed key | About $1 per month, prorated hourly |
| AWS managed key | No monthly fee |
| AWS owned key | No charge |
| Symmetric requests | About $0.03 per 10,000 requests, after a monthly free tier of 20,000 requests |
| Asymmetric and some other operations | Higher per-request prices, which vary by key spec |
Some details catch people out:
- AWS managed keys have no monthly fee, but their requests are billed. When S3 or EBS uses
aws/s3oraws/ebs, each call counts as a request in your account. - Every cryptographic call is a request.
Encrypt,Decrypt,GenerateDataKey,ReEncryptandGenerateMacall count. ADecrypton an S3GETis a request, just like aPutObjectthat callsGenerateDataKey. - Key rotation can add a small monthly charge. Automatic rotation of a customer managed key may be billed for rotated key material. Check the pricing page.
- Keys scheduled for deletion are not billed while they are pending deletion.
A quick estimate shows the scale. An application that reads 10 million SSE-KMS objects a month makes about 10 million Decrypt calls. That is 10,000,000 / 10,000 × $0.03, or about $30. At 1 billion reads it is about $3,000 a month. The cost is rarely a problem for small workloads. It matters for high-throughput data lakes, log pipelines and backup systems.
Request quotas
KMS applies request quotas per account and per Region. Cryptographic operations such as Encrypt, Decrypt and GenerateDataKey share one quota for symmetric keys. Asymmetric operations and GenerateMac have their own, usually much lower, quotas. Key facts:
- The shared symmetric quota is expressed in requests per second. It varies by Region, from thousands to tens of thousands per second. Look up the current number in Service Quotas under AWS Key Management Service.
- The quota is shared across all keys in the account and Region. One busy workload can starve another, even if they use different keys. This includes requests that AWS services make with your AWS managed keys.
- Management calls have separate, much lower quotas.
CreateKey,PutKeyPolicyandListKeysare examples. Don't call them on a hot path. - A request over the quota fails with
ThrottlingException. The call is rejected, not queued.
You can raise many of these quotas by opening a Service Quotas request. Do that only after you have reduced unnecessary calls. Asking for more quota is slower than designing for fewer requests.
Handle throttling in code
The AWS SDKs retry throttled calls. Configure them to retry with backoff, and prefer the adaptive mode, which slows the client down when it sees throttling.
import boto3
from botocore.config import Config
kms = boto3.client(
"kms",
config=Config(retries={"mode": "adaptive", "max_attempts": 10}),
)
resp = kms.generate_data_key(KeyId="alias/tutorial-key", KeySpec="AES_256")
print(len(resp["Plaintext"]))Retries only smooth out short bursts. If your steady-state rate is above the quota, retries will not save you.
Reducing calls with data key reuse
Envelope encryption already cuts the load for large payloads, because KMS handles only the small data key. Per-object envelope encryption still makes one KMS call per object, though. If you encrypt millions of small records, you can reuse one data key for a limited number of records.
The sketch below caches a data key for a short time and a limited number of uses. Each record stores the encrypted copy of the key that encrypted it.
import os
import time
import boto3
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
kms = boto3.client("kms")
CONTEXT = {"purpose": "demo"}
class DataKeyCache:
def __init__(self, key_id, max_age=60.0, max_uses=1000):
self.key_id = key_id
self.max_age = max_age
self.max_uses = max_uses
self._key = None
def get(self):
now = time.monotonic()
expired = self._key is None or (
now - self._key["created"] > self.max_age
or self._key["uses"] >= self.max_uses
)
if expired:
resp = kms.generate_data_key(
KeyId=self.key_id,
KeySpec="AES_256",
EncryptionContext=CONTEXT,
)
self._key = {
"plaintext": resp["Plaintext"],
"encrypted": resp["CiphertextBlob"],
"created": now,
"uses": 0,
}
self._key["uses"] += 1
return self._key["plaintext"], self._key["encrypted"]
cache = DataKeyCache("alias/tutorial-key")
def encrypt(plaintext: bytes) -> dict:
key, encrypted_key = cache.get()
nonce = os.urandom(12)
ciphertext = AESGCM(key).encrypt(nonce, plaintext, None)
return {"encrypted_key": encrypted_key, "nonce": nonce, "ciphertext": ciphertext}With these settings, 1,000 records cost one GenerateDataKey call instead of 1,000. On the read side, you can cache decrypted data keys the same way, keyed by the encrypted key bytes.
S3 Bucket Keys
S3 is where most teams first see KMS costs. With SSE-KMS and no Bucket Key, S3 calls KMS for every object. Each PutObject generates a data key and each GetObject calls Decrypt. A bucket with heavy traffic produces heavy KMS traffic.
An S3 Bucket Key is a bucket-level key that S3 derives from your KMS key. S3 calls KMS once to get the Bucket Key, then uses it to create the per-object data keys locally for a limited time. The objects are still encrypted under your KMS key's protection. AWS documents a reduction in KMS request costs of up to 99 percent for workloads with many objects.
Enable a Bucket Key
Set BucketKeyEnabled in the bucket's default encryption configuration. Don't rely on defaults here. The console and the API have not always agreed on the default, so state it explicitly.
aws s3api put-bucket-encryption \
--bucket my-example-bucket \
--server-side-encryption-configuration '{
"Rules": [
{
"ApplyServerSideEncryptionByDefault": {
"SSEAlgorithm": "aws:kms",
"KMSMasterKeyID": "alias/tutorial-key"
},
"BucketKeyEnabled": true
}
]
}'
aws s3api get-bucket-encryption --bucket my-example-bucketThings to know before relying on Bucket Keys
- They apply to new objects. Objects already in the bucket keep their per-object encryption. To switch them, copy them over themselves or use S3 Batch Operations.
- The encryption context changes. Without a Bucket Key, S3 uses the object ARN as the context. With one, it uses the bucket ARN. A key policy or IAM condition on
kms:EncryptionContext:aws:s3:arnthat names objects will stop matching. Update it to the bucket ARN. - CloudTrail shows far fewer KMS events. That is a benefit for log volume and cost. It also means you can no longer see a KMS event for every object access. Use S3 data events in CloudTrail if you need per-object auditing.
- They do not apply to dual-layer encryption (DSSE-KMS).
- They work with customer managed keys and with
aws/s3. Using a customer managed key lets you control the key policy and audit the key. - Bucket Keys are not a free pass on quotas. They lower the request rate. They don't remove the need to monitor throttling.
Finding where requests come from
Before you optimize, measure. Two sources help:
- CloudWatch metrics. Check the AWS/Usage metrics for KMS call counts, and watch for throttling errors in your application logs.
- CloudTrail. Query
kms.amazonaws.comevents and group byeventName,userIdentityand the encryption context. A single role callingDecryptmillions of times a day is your first target.
A common finding is one service or one job making repeated Decrypt calls for the same data key. That job is a candidate for caching or for a Bucket Key.
Decision guide
| Situation | Action |
|---|---|
| High-volume S3 SSE-KMS | Enable Bucket Keys |
| Millions of small records encrypted by your own code | Reuse data keys with a bounded cache |
| Occasional `ThrottlingException` bursts | Use SDK adaptive retries |
| Steady-state rate above quota | Reduce calls first, then request a quota increase |
| Strict per-object audit requirement | Weigh the audit benefit against the request cost, and use S3 data events |
Exercise
A bucket uses SSE-KMS with a customer managed key and a key policy that allows kms:Decrypt only when kms:EncryptionContext:aws:s3:arn equals arn:aws:s3:::reports/*. After you enable a Bucket Key, new object uploads start failing with access denied errors from KMS. Why, and how do you fix it?
Show answer
With a Bucket Key, S3 sends the bucket ARN (arn:aws:s3:::reports) as the encryption context value instead of the object ARN. The condition no longer matches. Change the policy condition to the bucket ARN, or remove the condition if it is no longer needed. Only the context-related statement needs to change.
Exercise
An application reads 200 million SSE-KMS objects a month from a bucket with no Bucket Key. Roughly what does it pay for KMS requests, and what is the estimated cost if a Bucket Key cuts requests by 99 percent? Use $0.03 per 10,000 requests and ignore the free tier.
Show answer
Without a Bucket Key, 200,000,000 / 10,000 × $0.03 = $600 per month. With a 99 percent reduction there are about 2,000,000 requests, which costs 2,000,000 / 10,000 × $0.03 = $6 per month.