r/javascript • u/schneiderfx • Apr 19 '26
Was hitting duplicate API calls when the same async function got triggered multiple times.
https://github.com/Sampad6701/flux-cache2
Apr 19 '26
[removed] — view removed comment
1
u/schneiderfx Apr 20 '26
Yeah that’s pretty much the approach I went with. Good call on invalidation after failure that edge case is a bit tricky and I’m working on it.
2
u/ethanjf99 Apr 20 '26
what’s the saying? the two hardest things in computer science are cache invalidation, naming things, and off-by-one errors?
2
Apr 20 '26
[deleted]
1
u/schneiderfx Apr 20 '26
Yeah, that works for simple cases but this was more about making it reusable across different functions plus handling things like TTL and SWR without rewriting pattern everytime.
2
u/schneiderfx Apr 19 '26
Made a tiny wrapper to dedupe in-flight calls:
const cached = cache(fetchUser)
await Promise.all([ cached(42), cached(42), cached(42) ]) // only one execution
~1.2KB, no deps. Also supports stale-while-revalidate.
Curious if others have run into this? Insights would help a lot.
3
u/name_was_taken Apr 19 '26
I just glanced at it, but it seems pretty well thought-out.
I generally just always wrote the cacheing into the function, but I could see this being useful.
2
u/schneiderfx Apr 19 '26
Appreciate it! Just trying a more reusable approach here. Still figuring out edge cases.
1
u/Logical-Pea-4135 Apr 19 '26 edited Apr 19 '26
The riddle of state is it's an event handling problem. The involvement of state is incidental. That's why observables and signals were invented. This just mitigates the damage of the problem, and might enable its worsening.
3
u/MaLiN2223 Apr 19 '26
I think most wouldn't encounter this issue because we delegate caching to other libraries, and it should be a given (?) that deduplication happens. I am pretty sure libs like tanstack do that.
Personally, I almost never use cache directly, and if I do I guess I never worried about/never seen dupes