Suppose I have DynamoDB table orders
which stores the orders created by each customer. The table has a column OrderId
(Primary Key), and a column CustomerId
. Customers can create create/delete orders.
If I want to implement a quota, say, each customer can place no more than, say, 1000 orders. How do I implement this?
One way is to query/count all existing orders of the customer in real time before customer tries to create a new order. I worry this will significantly degrade the performance of the API.
Another way is to create a separate table saving the total number of orders by each customer. every time before a new order is created, read this number, and increase by 1 if the quota is not reached, and return error if limit is reached. On the other hand, decrease this number by 1 if an Order is deleted.
Both strategies seem have concurrency issue. How to avoid race condition when multiple concurrent requests are trying to create a new order?
Any well known strategy for this task? Thanks in advance!
2 tables is the normal approach, but to avoid race conditions etc... you can just use TransactWriteItems. That will slow you to create new orders, with an UpdateItem along with a condition on the counter table. This is done in an ACID compliant fashion, ensuring accurate counts.
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/transaction-apis.html