Caching when relying on time
Hi. I have some questions about caching. If I have a function which is deterministic for 1 hour, every hour it will update, will this be cache? If not, what is the way of handling this caching behaviour?
16 Replies
If you use
Date.now()
I believe the function will be cached for 5 minutes.
You could use crons or an argument to cache the function for a full hour.can you show me a snippet of what the code looks like? I don't quite understand where that
Date.now()
appear in the api call
I cannot find any example
Date.now()
is a JavaScript built-in, you can call it in a query:
but do I have to return this Date.now() in the api?
I don't think it is needed right?
No, it gives you a UTC timestamp
You can base your logic on it
Just like if you were writing a JavaScript function for the browser
let's say myQuery will return a data, and this data will not be changed for an hour. If I call myQuery again within this hour, will it hit the cache and does that count as bandwidth?
I think that if you use Date.now() the query result will only be cached for 5 minutes
After 5 minutes it will be recomputed, even if results in the same value
Perhaps a cron that runs every hour is a better solution in your case?
https://docs.convex.dev/scheduling/cron-jobs
Cron Jobs | Convex Developer Hub
Convex allows you to schedule functions to run on a recurring basis. For
yes, I plan to use cron job to do it every hour. But within this hour, I want my data to be cached so that it is not taken from the database everytime and use the bandwidth
or do I misunderstand something?
If you use a cron, and you don't use Date.now() in your query, then yes, it will be cached for an hour (I think)
normally if I create my own API, I have control over the cache-control
but if I use Convex, I am not sure how this will be handled
I'm not 100% sure what our eviction policy is, but I'm pretty sure an hour will be fine, unless you have a ton of cached results
You can try this out (even in dev, your dev behaves exactly like your prod deployment)
ok thx. Thx for your prompt response
I would pass the time rounded to the hour as a parameter. That way it’s cached the full hour. If you calculate the time with Date.now() inside the function then convex doesn’t know when the time would result in a different result, so the caching will only be for a few seconds I believe.
Ah sorry didn’t read the whole thread. Cron that writes and query that reads whatever is there sounds great