Project: Multi-Tenant SaaS Keys and Isolation on DynamoDB
SaaS means many customers, one ops surface. Berlin PM Lena Vogt and Pune founder Vikram Patil ship TenantLite: TENANT# prefixes, IAM dynamodb:LeadingKeys, per-tenant email GSI, offboarding Query-delete. Reuse modeling; never trust client tenant id alone.
In this chapter
- Prefix every key with TENANT#
- Lock IAM with LeadingKeys
- Per-tenant unique email GSI
- Offboard a tenant safely
- Lab + cleanup
1. Everyday example: co-working mail slots
Each company gets a labeled slot. Staff must not open another company slot. Label = TENANT# prefix. Staff badge rules = IAM LeadingKeys.
2. Vertical steps
3. Purpose
One leaked Query without a tenant prefix is a breach headline. MNCs ask how isolation is enforced in data and IAM, not only in UI.
4. Overview
TenantLite shared table: PK=TENANT#tid SK=USER#|ORDER#|SETTINGS; GSI1 PK=TENANT#tid SK=EMAIL#email. IAM condition dynamodb:LeadingKeys = TENANT#tid from the auth token.
5. Steps
- List patterns per tenant (users, orders, settings, email lookup).
- Draw two tenants acme + beta sample items.
- Create lab-ddo-saas; Put acme users; Put beta users.
- Attach IAM role with LeadingKeys TENANT#acme; prove beta denied.
- GSI1 email unique per tenant; offboarding BatchWrite delete.
- Delete lab table.
6. Key sketch
| Entity | PK | SK |
|---|---|---|
| User | TENANT#acme | USER#u1 |
| Settings | TENANT#acme | SETTINGS |
| Email GSI | TENANT#acme | EMAIL#a@x.com |
7. Commands with output and meaning
aws dynamodb create-table --table-name lab-ddo-saas \
--attribute-definitions AttributeName=PK,AttributeType=S AttributeName=SK,AttributeType=S \
--key-schema AttributeName=PK,KeyType=HASH AttributeName=SK,KeyType=RANGE \
--billing-mode PAY_PER_REQUEST --region ap-south-1
aws dynamodb put-item --table-name lab-ddo-saas --item '{
"PK":{"S":"TENANT#acme"},"SK":{"S":"USER#u1"},"email":{"S":"a@acme.test"}}'
aws dynamodb query --table-name lab-ddo-saas \
--key-condition-expression "PK = :pk" \
--expression-attribute-values '{":pk":{"S":"TENANT#acme"}}'
# IAM sketch (attach to tenant role):
# "Condition":{"ForAllValues:StringLike":{"dynamodb:LeadingKeys":["TENANT#acme"]}}
# Meaning: role can only touch keys beginning TENANT#acme.
App binds tid from JWT, not from request body alone. GSI PK also starts with TENANT#.
8. Industry stories
- B2B CRM (Lena): workspace contacts.
- EdTech (Sofia): school→class→student.
- HealthTech (Meera): clinic-partitioned notes.
- FinTech (Omar): merchant ledgers.
- Logistics (Diego): shipper accounts.
- Media (Priya): publisher catalogs.
9. Lab
- Create lab-ddo-saas; put acme+beta; Query each.
- Document LeadingKeys policy; simulate deny for cross-tenant.
- Script tenant delete by Query PK; delete table.
Cleanup (stop billing)
- Delete lab resources you created.
- Confirm with describe that names are gone.
10. Ops checklist before you ship
- Confirm TTL attribute name and units (epoch seconds).
- Decide soft-delete vs hard-delete vs archive-to-S3.
- Enable PITR on any table you cannot rebuild from source.
- Document RPO/RTO and who runs restore drills.
- If multi-region: pick write stickiness and conflict rules.
- If DAX: prove cache-miss path and warm-up plan.
- Tag Owner + Expiry on every lab resource.
- Budget alert in the account before load tests.
11. Copy-paste DynamoDB CLI starters (batch 2)
export AWS_DEFAULT_REGION=ap-south-1
# TTL status
aws dynamodb describe-time-to-live --table-name ShopApp
# PITR / continuous backups
aws dynamodb describe-continuous-backups --table-name ShopApp
# On-demand backup
aws dynamodb create-backup --table-name ShopApp --backup-name lab-shop-$(date +%Y%m%d)
# List backups
aws dynamodb list-backups --table-name ShopApp
# Global table description (v2)
aws dynamodb describe-table --table-name ShopApp --query 'Table.Replicas'
12. More industry stories
- Retail (Aisha Khan, Dubai): TTL clears abandoned carts; soft-delete keeps 30-day undo.
- Bank (Lucas Meyer, Berlin): PITR on ledger table; restore drill every quarter.
- Travel (Omar Haddad, Amman): Global Tables for catalog reads; inventory writes sticky.
- Gaming (Carlos Rivera, Mexico City): DAX for hot profile Gets; never cache money ledgers.
- Social (Priya Nair, Kochi): adjacency edges for follows; sparse GSI for unread inbox.
- IoT (Mei Lin, Shenzhen): device#day PK + TTL 14 days; rollups to S3.
13. Glossary (batch 2)
| Term | Meaning |
|---|---|
| TTL | Time to Live — attribute with epoch seconds; DynamoDB deletes later |
| Soft delete | Flag deleted=true; item remains until TTL/archive |
| PITR | Point-in-time recovery — continuous backups window |
| Global Table | Multi-region replicated DynamoDB table |
| LWW | Last-writer-wins conflict resolution on replicas |
| DAX | DynamoDB Accelerator — in-memory cache cluster |
| Adjacency list | Edge items modeling relationships in one table |
| Fan-out | Write once; push copies to many feeds/inboxes |
14. Practice: explain out loud
- 60s: TTL vs soft-delete vs S3 archive.
- 60s: PITR vs on-demand backup.
- 60s: when Global Tables help and hurt.
- 60s: DAX consistency trade-off.
- 60s: CartLite checkout keys in one breath.
- 60s: follow edge vs feed item.
- Record once; cut filler; record again.
15. Safe lab hygiene
- Use ap-south-1 labs with a budget alert.
- Prefix lab tables with lab- and your initials.
- Delete replicas, DAX clusters, and backups you created for labs.
- Never enable Global Tables on production without a write plan.
- Tag every resource Owner + Expiry.
- Export/import labs can create large S3 bills — delete prefixes.
16. How this set links other chapters
- Data modeling — keys we reuse in projects.
- Transactions — checkout and seat patterns.
- Streams + Lambda — fan-out and CDC.
- CRUD survey — short TTL note we deepen.
- What Is DynamoDB? — intro.
17. Delete / archive decision pad
| Need | Prefer | Why |
|---|---|---|
| Undo 7-30 days | Soft-delete flag | User restore |
| Hard expiry, no read | TTL attribute | Auto delete later |
| Compliance keep cold | Export/archive to S3 | Cheap long store |
| Mistake recovery | PITR / backup | Table-level restore |
18. Ten oral drill questions
- What units does DynamoDB TTL use?
- Does TTL delete instantly?
- PITR window typical length?
- Global Tables conflict default?
- When sticky writes matter?
- DAX vs API Gateway cache?
- Cart PK for a shopper?
- Order lines under which PK?
- Follow edge SK example?
- Unread inbox sparse GSI idea?
19. RPO / RTO mini workshop
- Write the worst data loss you can accept (RPO) in minutes.
- Write how long restore may take (RTO) before business pain.
- Map: on-demand backup vs PITR vs multi-region replica.
- Schedule a restore drill on a lab table this month.
- Name the person who runs the drill.
20. Cost watch list (batch 2)
- PITR storage and on-demand backup storage.
- Global Tables: replicated WCUs in every region.
- DAX node hours even at idle.
- Export to S3 + S3 storage + Athena later.
- Streams + Lambda still bill during TTL deletes.
21. Project Definition of Done
- Access patterns written and peer-reviewed.
- Sample items drawn for happy path + one failure.
- Lab table created, exercised, deleted (or tagged Expiry).
- At least one conditional write or transaction exercised.
- Cleanup commands pasted in your notes.
- One interview answer recorded out loud.
22. Cross-links inside this batch
- TTL hygiene → Backup/PITR for “oops” recovery.
- Global Tables → sticky writes from capacity/hot lessons.
- DAX → only after Query shapes are correct.
- P1 CartLite reuses modeling + transactions.
- P2 Social reuses adjacency + Streams ideas.
23. Quick self-check (yes/no)
- I can explain TTL delay vs instant DeleteItem.
- I know when soft-delete beats hard delete.
- I can start PITR and say what restore costs in time.
- I can name one reason NOT to use Global Tables.
- I know DAX does not fix a bad partition key.
- I can sketch CartLite USER# and ORD# keys.
- I can sketch a follow edge item.
- I delete lab replicas/DAX/backups the same day.
24. Common errors and fixes
Each row is a real mistake students and juniors hit. Read the fix before you panic.
| Error / symptom | Fix |
|---|---|
| Client-supplied tenant id only | Bind from verified JWT. |
| IAM without LeadingKeys | Add dynamodb:LeadingKeys. |
| Email as global PK | Per-tenant GSI SK=EMAIL#. |
| Scan for admin UI | Tenant Query / export. |
| GSI without tenant prefix | GSI PK=TENANT#… |
| Noisy neighbor ignored | Isolate whale tenant table. |
| Soft offboard only | Query-delete + verify GSI empty. |
| Leave lab table | Delete same day. |
| Rewrite modeling chapter | Link modeling. |
25. Troubleshooting checklist
- Cross-tenant Get returns data: missing LeadingKeys / app bug.
- AccessDenied after login: tid mismatch vs role.
- Unique email clash: include TENANT# in GSI PK.
- Throttle one tenant: reserved capacity or split table.
- Backup restore mix: restore aside; migrate slice.
26. FAQ
Q. Should I always use a single table?
Often yes for related access patterns; not a religion. Separate tables are fine for unrelated domains or different capacity/security needs.
Q. Do I still need RDS?
Yes for heavy joins, multi-row SQL reports, and strong relational constraints. See the intro DynamoDB vs RDS chapter.
Q. Is Scan evil?
Scan is a tool for rare admin jobs and small tables. Design so hot paths use Query/GetItem.
Q. Where are Put/Get command details?
In the CRUD survey, CLI and SDK chapters — this deep set links them instead of copying.
Q. Table per tenant?
Start shared; split noisy tenants later.
Q. CMK per tenant?
Optional; start with table CMK.
Q. GDPR delete proof?
Query delete + GSI empty + ticket.
Q. LeadingKeys syntax?
ForAllValues:StringLike dynamodb:LeadingKeys.
27. Interview Q&A
Q. (B) Isolation key?
PK begins TENANT#tid.
Q. (B) IAM control?
dynamodb:LeadingKeys.
Q. (M) Unique email?
GSI under same tenant PK.
Q. (M) Offboard?
Query PK + batch delete + verify.
Q. (S/MNC) Noisy neighbor?
Dedicated table / capacity.
Q. (MNC) Trust client tid?
Never — JWT/session only.
28. Tips in English, Marathi and Hindi
Ravindra Bagale's Tip (EN)
TENANT# in every key + LeadingKeys — UI filters are not security.
Ravindra Bagale's Tip (MR)
प्रत्येक key ला TENANT# आणि LeadingKeys.
Tip (HI)
हर कुंजी में TENANT# और LeadingKeys — UI सुरक्षा नहीं।
Try at home
- Draw acme vs beta items.
- Write LeadingKeys policy stub.
- Offboard checklist on paper.
In short
- TenantLite = TENANT# collections.
- IAM LeadingKeys enforce.
- Offboard = Query delete.
- Cleanup labs.
Revision, interview and comparison cards
Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.








More cards: Ravi Sir's Cards.
Practice Tasks
Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.
About this scenarioLondon Legal LLP is a law business in London. Oliver Hughes looks after its IT and cloud work. They count money in GBP and run their AWS resources in the eu-west-2 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.
0 / 16
Easy Form a partition key from the authorised tenant
The authenticated tenant is acme. Using the TENANT#tid convention, what exact partition key should the request use?
- Read the situation and identify what you need to decide.
- Work through the relevant concept or calculation.
- Enter only the requested term or number.
- Check your answer, then read the explanation.
Easy Name a condition that limits partition-key access
Which DynamoDB IAM condition key can restrict supported calls to a partition key matching the authorised tenant?
- Read the situation and identify what you need to decide.
- Work through the relevant concept or calculation.
- Enter only the requested term or number.
- Check your answer, then read the explanation.
Easy Use authenticated tenant context for a request
The JSON body claims the caller belongs to tenant-2. What validated token element should the app check against its tenant permissions before trusting an identity supplied by JWT?
- Read the situation and identify what you need to decide.
- Work through the relevant concept or calculation.
- Enter only the requested term or number.
- Check your answer, then read the explanation.
Easy Enforce uniqueness beyond a lookup index
Two users in one tenant submit the same email at once. A GSI can find existing records but cannot enforce uniqueness by itself. Which DynamoDB operation can atomically write a uniqueness marker and the user item?
- Read the situation and identify what you need to decide.
- Work through the relevant concept or calculation.
- Enter only the requested term or number.
- Check your answer, then read the explanation.
Easy Describe saas table
CLI.
Describe table ShopApp
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Easy Tenant key YAML
Sketch.
YAML: pk: TENANT#acme, sk: USER#u1.
- Start from the top-level keys the task names.
- Indent child keys with 2 spaces (no tabs).
- Fill in each property with the value from the task.
- Click Check answer. Key order does not matter.
Easy Confirm removal from an old secondary access path
A tenant’s base records were removed but its GSI still returns matches immediately afterwards. Which read consistency can explain that temporary result?
- Read the situation and identify what you need to decide.
- Work through the relevant concept or calculation.
- Enter only the requested term or number.
- Check your answer, then read the explanation.
Medium List the records for one authorised offboarding operation
A lab has one partition key per tenant and the admin knows the exact tenant key. Which DynamoDB operation should page through only that tenant’s item collection before targeted deletion?
- Read the situation and identify what you need to decide.
- Work through the relevant concept or calculation.
- Enter only the requested term or number.
- Check your answer, then read the explanation.
Medium Avoid enumerating all tenants for one lookup
The admin needs one tenant’s reports and knows the tenant partition key. Which read operation should replace a full table Scan?
- Read the situation and identify what you need to decide.
- Work through the relevant concept or calculation.
- Enter only the requested term or number.
- Check your answer, then read the explanation.
Medium Keep an index partition within the tenant boundary
You are designing the alternate customer lookup and need a tenant boundary. Which trusted identifier should form part of the GSI partition key?
- Read the situation and identify what you need to decide.
- Work through the relevant concept or calculation.
- Enter only the requested term or number.
- Check your answer, then read the explanation.
Medium Isolate the largest tenant’s capacity
One customer needs an independent capacity and backup boundary from other tenants. Which DynamoDB resource supplies that boundary without sharing a primary table?
- Read the situation and identify what you need to decide.
- Work through the relevant concept or calculation.
- Enter only the requested term or number.
- Check your answer, then read the explanation.
Medium IAM key YAML
Name.
YAML: condition_key: dynamodb:LeadingKeys.
- Start from the top-level keys the task names.
- Indent child keys with 2 spaces (no tabs).
- Fill in each property with the value from the task.
- Click Check answer. Key order does not matter.
Hard Identify a pooled tenant architecture
Many small tenants use one DynamoDB table with partition keys that include each tenant ID. Name this arrangement.
- Read the situation and identify what you need to decide.
- Work through the relevant concept or calculation.
- Enter only the requested term or number.
- Check your answer, then read the explanation.
Hard Pick the boundary that has to reject an unauthorised call
A client-side filter hides other tenants, but a direct API request asks for a different tenant key. Which layer must reject the request?
- Read the situation and identify what you need to decide.
- Work through the relevant concept or calculation.
- Enter only the requested term or number.
- Check your answer, then read the explanation.
Hard Check that the intended sandbox table was removed
After deleting this project’s disposable table, which read-only DynamoDB API should report that its table resource can no longer be found?
- Read the situation and identify what you need to decide.
- Work through the relevant concept or calculation.
- Enter only the requested term or number.
- Check your answer, then read the explanation.
Hard Name the data-design input before building tenant keys
The team has not decided how to read a user, query an email index or offboard a tenant. What should it list before choosing its PK/SK shapes?
- Read the situation and identify what you need to decide.
- Work through the relevant concept or calculation.
- Enter only the requested term or number.
- Check your answer, then read the explanation.