Decrementing a count property by 1 with KV and Promise.all
Hi!
I'm using workers KV to keep track of # of credits a user has (the count property).
i.e.
{user1234: {credits: 10}}
In my client application, I'm using Promise.all
to make multiple requests to an endpoint on my Worker /decrementCreditsByOne
which does what the name implies.
It works great locally, but on the deployed worker, The count loses track.
My app frequently uses Promise.all
to call /decrementCreditsByOne
at least 10 times.
the function essentially gets
the JSON from KV using the unique key, decrement the credits by 1, then puts
the value back in with the updated credits.
Is KV the wrong choice here? Would Durable Objects, or D1 be better? What would you recommend? Should this work and my logic is just wrong?
Also, I noticed timestamps aren't really a thing with KV. They aren't a requirement for my app but would be nice to have!5 Replies
ChatGPT says to use DO but I would love to hear what the humans say too!
https://chat.openai.com/share/68757cf5-eafb-4248-80d8-28d28b5bfefc
ChatGPT
A conversational AI system that listens, learns, and challenges
KV is indeed the wrong choice as it is eventually consistent and not meant for a lot of writes. Think web assets, not typical database tasks
As a fellow human, I agree with ChatGPT for once, DOs or D1 is your best bet. D1 is built on DOs so not too much different, except with DOs it'd be easier to make one per user and have it be closest to the user/lower latency
Thank you @Chaika - Refactor here I come!
Yea DOs are cheaper then KV anyway for your use,
$0.20 / mil reads, $1.00/mil writes, $0.20 Gb-month stored (reads/writes in 4 KB chunks, which you're not going to pass with a number. KV is $0.50/mil reads, $5/mil writes and $0/50 GB-month stored
I'm a long way from those numbers but maybe some day... haha