In this repository I have recreated/simulated a problem I faced at work some time ago.
Here I show three different ways to solve the problem:
- Linear approach (Less optimal solution)
- Using pipelines
- Using pipelines and semaphores (Most optimal solution)
⚠️ Remember: the patterns are a conceptual idea more than a strict way to do something.
Calculate the net profit for each closing in a company's stores.
A company operates stores
Each store has multiple closings (accounting periods, such as monthly or quarterly)
For every closing, the company tracks:
salesRevenue generated during the period.costsExpenses incurred to run the store during the period.
Develop a process to calculate and store the net profit of each close, where net profit = sales - costs
⚠️ Some details have been changed to avoid revealing confidential information but the problem remains the same.
The process runs every 6 hours on weekdays, so it runs on AWS Lambda (EventBridge) to save costs, and as is well known, AWS Lambda has a maximum timeout of 15 minutes. So, the idea is not to exceed the timeout. See how to determine the appropriate timeout value for a Lambda function
Linear (See the code)
make lineal
time ./build/linealmake benchmark_linealPipelines (See the code)
make pipeline
time ./build/pipelinemake benchmark_pipelinePipelines + Semaphores (See the code)
make semaphore
time ./build/semaphoremake benchmark_semaphoregoos: darwin
goarch: arm64
pkg: github.com/yael-castro/pipelines/internal/logic
cpu: Apple M4
│ lineal.out │ semaphore.out │
│ sec/op │ sec/op vs base │
Logic_CalculateProfit 328497.6m ± 3% 272.8m ± 4% -99.92% (p=0.000 n=10)
│ lineal.out │ semaphore.out │
│ B/op │ B/op vs base │
Logic_CalculateProfit 41.31Mi ± 0% 47.29Mi ± 0% +14.48% (p=0.000 n=10)
│ lineal.out │ semaphore.out │
│ allocs/op │ allocs/op vs base │
Logic_CalculateProfit 129.9k ± 0% 188.0k ± 1% +44.70% (p=0.000 n=10)
⚠️ The benchmarks were performed using only one logic CPU at a time._ = runtime.GOMAXPROCS(1)