I'm working on a website that mostly displays items created by registered users. So I'd say 95% of API calls are to read a single item and 5% are to store a single item. System is designed with AWS API Gateway that calls AWS Lambda function which manipulates data in DynamoDB.
My next step is to implement voting system (upvote/downvote) with basic fetaures:
- Each registered user can vote only once per item, and later is only allowed to change that vote.
- number of votes needs to be displayed to all users next to every item.
- items have only single-item views, and are (almost) never displayed in a list view.
- only list view I need is "top 100 items by votes" but it is ok to calculate this once per day and serve cached version
My goal is to design a database/lambda to minimize costs of AWS. It's easy to make the logic work but I'm not sure if my solution is the optimal one:
- My
items
table currently has hashkeyslug
and sortkeyversion
- I created
items-votes
table with hashkeyslug
and sortkeyuser
and alsovoted
field (containing -1 or 1) - I added field
votes
toitems
table - API call to upvote/downvote inserts to
item-votes
table but before checks constraints that user has not already voted that way. Then in second query updatesitems
table with updated votes count. (so 1 API call and 2 db queries) - old API call to show an item stays the same but grabs new
votes
count too (1 API call and 1 db query)
I was wondering if this can be done even better with avoiding new items-votes
table and storing user votes inside items
table? It looks like it is possible to save one query that way, and half the lambda execution time but I'm worried it might make that table too big/complex. Each user
field is a 10 chars user ID so if item gets thousands of votes I'm not sure how Lambda/DynamoDB will behave compared to original solution.
I don't expect thousands of votes any time soon, but it is not impossible to happen to a few items and I'd like to avoid situation where I need to migrate to different solution in the near future.