IAM is DynamoDB's authorisation layer and it goes further than most people use it. A policy grants specific actions (dynamodb:GetItem, Query, PutItem) on specific resources - and the resource ARN can name an index, so you can grant query access to one GSI without granting it on the base table.
Item-level and attribute-level conditions are the part worth learning. dynamodb:LeadingKeys restricts a principal to partition key values matching a condition - typically their own identity, via a variable from a Cognito or federated identity. That gives genuine multi-tenant isolation enforced by IAM rather than by application code: a caller simply cannot read another tenant's partition. And dynamodb:Attributes with dynamodb:Select restricts which attributes a principal may read or write.
The permissions to withhold deliberately: dynamodb:DeleteTable, UpdateTable, DeleteBackup, UpdateContinuousBackups (which can disable PITR), and dynamodb:Scan on large tables, where a careless call is a real cost event. Note that dynamodb:* on Resource: "*" is the policy that most "temporary" development roles end up with and the one most often found still in production.
Encryption at rest is always on. The choice is the key: an AWS-owned key (default, free), an AWS-managed key, or a customer-managed KMS key, which gives you key rotation, an audit trail of key use in CloudTrail, and the ability to revoke access to the data by revoking the key. A customer-managed key adds a KMS request cost per operation, which on a high-throughput table is a real line item.
VPC endpoints keep traffic to DynamoDB inside the AWS network rather than over the public internet. A gateway endpoint for DynamoDB is free and should be the default for anything in a VPC. The endpoint policy can further restrict which tables are reachable from that VPC, which is useful defence in depth.
Monitoring. The metrics that matter: ThrottledRequests and the read and write throttle events, SuccessfulRequestLatency by operation, ConsumedCapacity against provisioned, SystemErrors, UserErrors, ConditionalCheckFailedRequests (whose rate tells you about contention), ReplicationLatency for global tables, and AgeOfOldestUnreplicatedRecord plus stream iterator age for consumers. CloudTrail records control-plane calls, which is how you find out who deleted the table.
Infrastructure as code is not optional at this level. A DynamoDB table's key schema cannot be changed, several properties force replacement, and LSIs can only be created with the table - so the table definition must be reviewable and reproducible. CloudFormation, CDK or Terraform. The specific hazard: a CloudFormation change that replaces a table deletes the old one, so DeletionPolicy: Retain and UpdateReplacePolicy: Retain belong on every production table resource.
Quotas that bound a design: 2,500 tables per region per account (soft), 20 GSIs and 5 LSIs per table, 100 items or 4 MB per transaction, 25 items or 16 MB per batch write, 100 items or 16 MB per batch get, 1 MB per query or scan page, 400 KB per item, and per-table throughput defaults that are raisable. Knowing these prevents designs that cannot be deployed.
Laboratory exercise 6 - make it defensible.
Define the whole stack as infrastructure as code, with retention policies, and deploy it.
Implement least privilege: an application role with only the actions and resources it needs; a role restricted by LeadingKeys to one tenant's partitions; a read-only reporting role with access to one GSI and not the base table; and a monitoring role with CloudWatch access and no table access. Test every denial.
Demonstrate the multi-tenant isolation: assume the tenant-restricted role and attempt to read another tenant's partition, and capture the denial. This is IAM enforcing a business rule, and it is worth seeing work.
Configure a customer-managed KMS key, and demonstrate that revoking access to the key makes the data unreadable.
Create a VPC gateway endpoint and show traffic staying off the public internet. Add an endpoint policy restricting which tables are reachable.
Configure monitoring with all the alarms above and thresholds for each.
Then produce the quota review: for each quota above, state where your design sits relative to it.
Deliverable: the infrastructure as code with retention policies, the IAM policies, a test script attempting every forbidden operation with its output, the tenant isolation demonstration, the KMS revocation evidence, the VPC endpoint configuration, the alarm definitions with thresholds, the quota review, and a deployment and cost checklist.
// ================= IAM, with ITEM-LEVEL conditions =================
// The application role: only what it needs, on what it needs.
const appPolicy = {
Version: "2012-10-17",
Statement: [
{ Sid: "TableAccess", Effect: "Allow",
Action: ["dynamodb:GetItem", "dynamodb:BatchGetItem",
"dynamodb:Query", "dynamodb:PutItem",
"dynamodb:UpdateItem", "dynamodb:DeleteItem",
"dynamodb:TransactWriteItems", "dynamodb:TransactGetItems"],
Resource: [
"arn:aws:dynamodb:eu-west-2:111122223333:table/Commerce",
// THE RESOURCE ARN CAN NAME AN INDEX. Grant query on one GSI
// without granting it on the base table:
"arn:aws:dynamodb:eu-west-2:111122223333:table/Commerce/index/GSI1"
]},
// NO dynamodb:Scan. A careless Scan on a large table is a real
// cost event, and withholding it is cheaper than explaining it.
{ Sid: "DenyDestructive", Effect: "Deny",
Action: ["dynamodb:DeleteTable", "dynamodb:UpdateTable",
"dynamodb:DeleteBackup",
// This one can DISABLE PITR, which removes your only
// recovery from a bad deployment:
"dynamodb:UpdateContinuousBackups"],
Resource: "*" }
]
};
// dynamodb:* on Resource "*" is the policy most "temporary"
// development roles end up with and the one most often still in
// production. Grep for it.
// ================= MULTI-TENANT ISOLATION, ENFORCED BY IAM =========
// THE part of DynamoDB IAM worth learning. A caller simply CANNOT
// READ another tenant's partition - not because the application
// filters, but because IAM refuses.
const tenantPolicy = {
Version: "2012-10-17",
Statement: [{
Effect: "Allow",
Action: ["dynamodb:GetItem","dynamodb:Query","dynamodb:PutItem",
"dynamodb:UpdateItem"],
Resource: "arn:aws:dynamodb:eu-west-2:111122223333:table/Commerce",
Condition: {
"ForAllValues:StringLike": {
// Only partition keys matching THIS CALLER'S identity:
"dynamodb:LeadingKeys": [
"TENANT#${aws:PrincipalTag/tenantId}#*",
"USER#${cognito-identity.amazonaws.com:sub}"
]
},
// ATTRIBUTE-level: which attributes may be touched at all.
"ForAllValues:StringEquals": {
"dynamodb:Attributes": ["PK","SK","status","total","itemCount",
"updatedAt","quantity","sku"]
},
"StringEqualsIfExists": {
"dynamodb:Select": "SPECIFIC_ATTRIBUTES"
}
}
}]
};
// Demonstrate it: assume the role, query another tenant's partition:
// AccessDeniedException: User: arn:aws:sts::...:assumed-role/tenant-a
// is not authorized to perform: dynamodb:Query on resource ...
// IAM enforcing a business rule. Worth seeing work once.
// A reporting role: ONE GSI, and NOT the base table:
// Action: ["dynamodb:Query"]
// Resource: ".../table/Commerce/index/GSI1"
// (querying the base table is simply not granted)
// VERIFY THE DENIALS - the assessed part. Every one must fail:
// Scan -> AccessDeniedException
// DeleteTable -> AccessDeniedException
// UpdateContinuousBackups -> AccessDeniedException
// Query another tenant's PK -> AccessDeniedException
// Update a non-permitted attr -> AccessDeniedException
// ================= KMS =============================================
// Encryption at rest is ALWAYS ON. The choice is the KEY:
// AWS-owned default, free, no visibility
// AWS-managed in your account, CloudTrail logs key use
// CUSTOMER-MANAGED rotation, an audit trail, and the ability to
// REVOKE ACCESS TO THE DATA by revoking the key
//
// aws dynamodb update-table --table-name Commerce \
// --sse-specification Enabled=true,SSEType=KMS,\
//KMSMasterKeyId=arn:aws:kms:eu-west-2:111122223333:key/abcd-1234
//
// A customer-managed key adds a KMS REQUEST COST PER OPERATION. On a
// high-throughput table that is a real line item - put it in the
// cost model. Demonstrate the revocation; it is the capability you
// are paying for.
// ================= VPC endpoint ====================================
// aws ec2 create-vpc-endpoint --vpc-id vpc-abc123 \
// --service-name com.amazonaws.eu-west-2.dynamodb \
// --route-table-ids rtb-abc123
//
// A GATEWAY endpoint for DynamoDB is FREE and should be the default
// for anything in a VPC - traffic stays inside the AWS network. The
// ENDPOINT POLICY can further restrict which tables are reachable
// from that VPC, which is useful defence in depth:
// { "Statement": [{ "Effect": "Allow", "Principal": "*",
// "Action": "dynamodb:*",
// "Resource": ".../table/Commerce" }] }
// ================= INFRASTRUCTURE AS CODE: not optional ============
// A table's KEY SCHEMA CANNOT BE CHANGED, several properties FORCE
// REPLACEMENT, and LSIs can ONLY be created with the table. So the
// definition must be reviewable and reproducible.
//
// Resources:
// CommerceTable:
// Type: AWS::DynamoDB::Table
// # THE SPECIFIC HAZARD: a CloudFormation change that REPLACES
// # the table DELETES THE OLD ONE. These two lines belong on
// # EVERY production table resource:
// DeletionPolicy: Retain
// UpdateReplacePolicy: Retain
// Properties:
// TableName: Commerce
// BillingMode: PAY_PER_REQUEST
// AttributeDefinitions: [...]
// KeySchema: [...]
// GlobalSecondaryIndexes: [...]
// PointInTimeRecoverySpecification:
// PointInTimeRecoveryEnabled: true
// TimeToLiveSpecification:
// AttributeName: ttl
// Enabled: true
// StreamSpecification:
// StreamViewType: NEW_AND_OLD_IMAGES
// SSESpecification:
// SSEEnabled: true
// ================= MONITORING: what to alarm on ====================
// ThrottledRequests > 0 sustained capacity or a hot key
// Read/WriteThrottleEvents per index too
// SuccessfulRequestLatency p99 by operation
// ConsumedCapacity / Provisioned > 80%
// SystemErrors > 0 AWS-side
// UserErrors rising a client bug
// ConditionalCheckFailedRequests rate CONTENTION - a
// useful signal, not an error rate
// ReplicationLatency global tables
// GetRecords.IteratorAgeMillis a stream consumer FALLING BEHIND;
// at 24 h you LOSE RECORDS
// AccountProvisionedCapacity account-level ceilings
//
// CloudTrail records CONTROL-PLANE calls - which is how you find
// out who deleted the table.
// ================= QUOTAS that bound a design ======================
// tables per region per account 2,500 (soft)
// GSIs per table 20
// LSIs per table 5 (creation only)
// items per transaction 100 or 4 MB
// items per BatchWriteItem 25 or 16 MB
// items per BatchGetItem 100 or 16 MB
// query/scan page 1 MB
// item size 400 KB
// partition key length 1-2048 bytes
// sort key length 1-1024 bytes
// per-table throughput default raisable, per region
//
// For each one, state where your design sits. Knowing them prevents
// designs that cannot be deployed - a 150-item transaction, say,
// which looks fine until it does not.
// aws service-quotas list-service-quotas --service-code dynamodb
Open this example in the editor and change it. Nothing you type is saved.
Discussion
No questions on this topic yet. Sign in to ask the first one.