KV strange behaviour

KV sometimes returns wrong value, I have a logic something like this :

count = kv.get(key),
count++,
kv.put(key, count).

So whenever I get count it must always be bigger than the previous one right? But sometimes it returns some smaller number. It would be great if you allowed to share a video of the problem.

Example count = 97, I reload the page and it shows count = 94

Here is the code

async function handleRequest(request) {

  var count = await userCount.get("count");

  var retVal = {
    "count":count,
  };

  var json = JSON.stringify(retVal);

  count++;
  await userCount.put("count", count);

  return new Response(json, {
    headers: {
      "Content-Type": "text/json"
    }
  })

}

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request));
});

KV is eventually consistent, when you update a value it won’t update immediately. It can take up to 60 seconds (worst case).

The eventually consistent nature is the cause here. You get, that value is cached. You put and then get again, it’ll grab the cached value.

Docs: KV · Cloudflare Workers docs

Durable Objects are strongly consistent and ideal for counters like this. Docs: Durable Objects · Cloudflare Workers docs

Interesting… Is there any way to use storage without KV? Like read and write from firestore? It’s just a test project not willing to pay $5 yet