Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Singleflight Concurrency Design Pattern In Golang

Sign upSign InSign upSign InRyo KusnadiFollowLevel Up Coding--ListenShareIn this article, I will share one of rarely used concurrency that we have in go. Start from the concept, advantage, disadvantage, and the usecasessingleflight (golang.org/x/sync/singleflight) is a concurrency method to prevent duplicate work from being executed due to multiple calls for the same resource. In another words, it provides a repeatable function call suppression mechanism by assigning a key to each function call. When functions with the same key are called concurrently, they will only be executed once and return the same result. Its essence is to reuse the results of function callsBasically, there are only 3 method for the single flightAlso we can deep dive into the code singleflight/singleflight.go , it’s pretty straightforward. In the Do method, it is mainly controlled by waitgroup. The main process is as follows:To implement the Singleflight concurrentcy, we can implement it using the Group as below example (Github Repo):Benchmark:BenchmarkSimulateConcurrentProcessesWithNoSf-12: This benchmark represents the performance without using the singleflight package. It took an average of 6350 nanoseconds per operation, with an average allocation of 176 bytes and 11 allocations per operation.BenchmarkSimulateConcurrentProcessesWithSf-12: This benchmark represents the performance when using the singleflight package. It took an average of 12330 nanoseconds per operation, with an average allocation of 1028 bytes and 28 allocations per operation.Logging:From these results, we can conclude that using the singleflight package introduces a performance overhead, leading to increased time per operation, more memory allocation, and more allocations per operation compared to not using it. However, it's important to note that the singleflight package is beneficial in scenarios where multiple goroutines request the same resource simultaneously, preventing redundant work and improving overall performance in such scenarios.----Level Up CodingSoftware Engineer At E-Commerce StartupRyo KusnadiinLevel Up Coding--Arslan AhmadinLevel Up Coding--21Arslan AhmadinLevel Up Coding--30Ryo KusnadiinLevel Up Coding--Simeon GrancharovinStackademic--5Harendra Kumar--Mert ÇAKMAKinGoTurkiye--Ryo KusnadiinLevel Up Coding--Mou Sam Dahal--1Metakratos StudioinMetakratos Studio--HelpStatusAboutCareersBlogPrivacyTermsText to speechTeams



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

Singleflight Concurrency Design Pattern In Golang

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×