logoalt Hacker News

mholtyesterday at 10:47 PM3 repliesview on HN

First I've heard of this. Lazyweb, why would I use this over sync.Once?


Replies

kevin_nisbetyesterday at 11:14 PM

singleflight and sync.Once handle slightly different use cases.

sync.Once - Run exactly once, only the first call is invoked.

singleflight - Merge concurrent requests into one request and return the response to all the callers.

Where I tend to use both, is sync.Once tends to get used for lazy init code, the first caller does any client initializations, and subsequent callers wait, and then the lazy init is done and never done again in the lifetime of the application.

For singleflight, it tends to be on merging relatively expensive requests together. Like retrieving and parsing a JSON object from a server in concurrent requests. Merging those requests together, doing the expensive work once and distributing the results to each concurrent caller type of idea. With the results becoming invalid over time so a later set of requests need to do it all over again.

hnavyesterday at 10:56 PM

sync.Once is for performing lazy initialization once in a process' lifetime. This is for duplicative requests for the same resource. E.g. concurrent requests for the same cache key can be coalesced into a single call. You can use this to prevent the connection setup thundering herd that often occurs when a bunch of requests come in for the same destination with an empty connection pool, etc.

0x696C6961yesterday at 10:51 PM

It has error handling.