Repository navigation
Description
What?
Create a multi-language guide to cover the importance of thinking about concurrency for improving performance. It can make a significant impact, but many users aren't familiar with it. No need to be exhaustive, just the essential for dagger, an example, and sharing resources to learn more.
### Common
- [ ] Simple concurrency explanation (an analogy and images may help)
### Language specific
- [ ] Example
- [ ] Explanation
- [ ] Learning resources
Overview
The Dagger engine will do what it can to maximize parallelism, but you need to send those API requests in the first place. In common synchronous code, you do one request and wait for it’s response before sending the next request.
There’s an obvious bottleneck here in waiting for the responses, which can take a long time, depending on the workload. So, whenever it makes sense to run multiple things at the same time, it pays to use your language’s concurrency features (if it supports it) to continue sending more requests while you wait for the responses.
Example
Go, Python and NodeJS support concurrency. Notice they have a similar result on the same use cases because they share the same bottleneck (i.e., waiting for the network response).
Go SDK
gantt
title Go SDK with and without concurrency
dateFormat x
axisFormat %M:%S
section Sync
Test X : 0, 30795
Test Z : 30795, 61450
Test Y : 61450, 92117
section Async
Test Z : 0, 35705
Test Y : 0, 35706
Test X : 0, 35709
Full code
package main
import (
"context"
"fmt"
"time"
"dagger.io/dagger"
"golang.org/x/sync/errgroup"
)
func main() {
ctx := context.Background()
client, err := dagger.Connect(ctx)
if err != nil {
panic(err)
}
defer client.Close()
fmt.Println("```mermaid")
fmt.Println("gantt")
fmt.Println("title Go SDK with and without concurrency")
fmt.Println("dateFormat x")
fmt.Println("axisFormat %M:%S")
fmt.Println("")
fmt.Println("section Sync")
if err := sync(client, ctx); err != nil {
panic(err)
}
fmt.Println("")
fmt.Println("section Async")
if err := async(client, ctx); err != nil {
panic(err)
}
fmt.Println("```")
}
func sync(c *dagger.Client, ctx context.Context) error {
start := millis()
if err := testX(start, c, ctx); err != nil {
return err
}
if err := testZ(start, c, ctx); err != nil {
return err
}
if err := testY(start, c, ctx); err != nil {
return err
}
return nil
}
func async(c *dagger.Client, ctx context.Context) error {
eg, gctx := errgroup.WithContext(ctx)
start := millis()
eg.Go(func() error {
return testX(start, c, gctx)
})
eg.Go(func() error {
return testZ(start, c, gctx)
})
eg.Go(func() error {
return testY(start, c, gctx)
})
return eg.Wait()
}
func testX(s int64, c *dagger.Client, ctx context.Context) error {
return run("Test X", s, c, ctx)
}
func testY(s int64, c *dagger.Client, ctx context.Context) error {
return run("Test Y", s, c, ctx)
}
func testZ(s int64, c *dagger.Client, ctx context.Context) error {
return run("Test Z", s, c, ctx)
}
func run(label string, start int64, c *dagger.Client, ctx context.Context) error {
before := millis() - start
_, err := c.
Container().
From("alpine").
WithEnvVariable("NOCACHE", fmt.Sprintf("%s:%s", label, time.Now())).
WithExec([]string{"sh", "-c", "sleep 30"}).
ExitCode(ctx)
if err != nil {
return err
}
after := millis() - start
fmt.Printf("%s : %d, %d\n", label, before, after)
return nil
}
func millis() int64 {
return time.Now().UnixNano() / int64(time.Millisecond)
}Note
You can see more realistic examples in our own Dagger CI code. For example, since each SDK’s pipelines are independent from each other, it makes sense to run them concurrently.
Not concurrent
func test(c *dagger.Client, ctx context.Context) error {
if err := testX(c, ctx); err != nil {
return err
}
if err := testZ(c, ctx); err != nil {
return err
}
if err := testY(c, ctx); err != nil {
return err
}
return nil
}Concurrent
func test(c *dagger.Client, ctx context.Context) error {
eg, gctx := errgroup.WithContext(ctx)
eg.Go(func() error {
return testX(c, gctx)
})
eg.Go(func() error {
return testZ(c, gctx)
})
eg.Go(func() error {
return testY(c, gctx)
})
return eg.Wait()
}Python SDK
gantt
title Python SDK with and without concurrency
dateFormat x
axisFormat %M:%S
section Sync
Test X : 0, 31182
Test Y : 31182, 61831
Test Z : 61831, 93331
section Async
Test Y : 3, 30704
Test X : 0, 30707
Test Z : 4, 30707
Full code
import time
import uuid
import anyio
import dagger
async def main():
async with dagger.Connection() as client:
print("```mermaid")
print("gantt")
print("title Python SDK with and without concurrency")
print("dateFormat x")
print("axisFormat %M:%S")
print()
print("section Sync")
await sync(client)
print()
print("section Async")
await async_(client)
print("```")
async def sync(client: dagger.Client):
start = millis()
await testX(start, client)
await testY(start, client)
await testZ(start, client)
async def async_(client: dagger.Client):
start = millis()
async with anyio.create_task_group() as tg:
tg.start_soon(testX, start, client)
tg.start_soon(testY, start, client)
tg.start_soon(testZ, start, client)
async def testX(start: int, client: dagger.Client):
return await run("Test X", start, client)
async def testY(start: int, client: dagger.Client):
return await run("Test Y", start, client)
async def testZ(start: int, client: dagger.Client):
return await run("Test Z", start, client)
async def run(label: str, start: int, client: dagger.Client):
before = millis() - start
await (
client
.container()
.from_("alpine")
.with_env_variable("NOCACHE", str(uuid.uuid4()))
.with_exec(["sh", "-c", "sleep 30"])
.exit_code()
)
after = millis() - start
print(f"{label} : {before}, {after}")
def millis():
return int(round(time.time() * 1000))
anyio.run(main)Note
You can see more realistic examples for testing the popular FastAPI library agains multiple python versions in a synchronous way (~3m) vs using concurrency (~1m). Since testing the same test suite against multiple Python versions are independent from each other, it makes sense to run them concurrently.
Testing the FastAPI library with and without concurrency
gantt
title Testing the FastAPI library with and without concurrency
dateFormat x
axisFormat %M:%S
section await
Python 3.7 : 68, 37831
Python 3.8 : 37873, 63971
Python 3.9 : 64010, 97783
Python 3.10 : 97824, 128072
Python 3.11 : 128109, 162619
section task group
Python 3.7: 48, 51079
Python 3.8: 58, 50979
Python 3.9: 52, 51978
Python 3.10: 55, 52633
Python 3.11: 56, 59450
Not concurrent
async def test(client: dagger.Client):
await testX(client)
await testY(client)
await testZ(client)Concurrent
async def test(client: dagger.Client):
async with anyio.create_task_group() as tg:
tg.start_soon(testX, client)
tg.start_soon(testY, client)
tg.start_soon(testZ, client)But aren’t I using “async” with await?
Each time you use an await, your code is “stuck“ in that line until it gets a result. It doesn’t block the event loop, but that specific (parent) coroutine won’t make any progress until something is returned (unless there’s more work available from the event loop queue). This is what’s happening in the non-concurrent example.
Using a task group however, each test is encapsulated in their own coroutine that can be started, paused, restarted, etc… When a coroutine is paused because it’s waiting on blocking I/O (network request in this case), the event loop picks the next one available in the queue. So in effect you’ll make all the requests first, and then wait for all the responses. Only then can the engine do it’s thing running as many things in parallel as it can.
If you only have awaits and not using any concurrency features such as a task group, then there won’t be anything in the event loop queue to pick up while you wait. Thus, even though you’re using async/await, it behaves like the usual synchronous code.
Resources
Node.js SDK
gantt
title Node.js SDK with and without concurrency
dateFormat x
axisFormat %M:%S
section Sync
Test X : 0, 31719
Test Y : 31719, 62397
Test Z : 62398, 93110
section Async
Test X : 0, 30669
Test Z : 1, 30671
Test Y : 0, 30673
Full code
import Client, { connect } from "@dagger.io/dagger"
connect(async (client: Client) => {
console.log("```mermaid")
console.log("gantt")
console.log("title NodeJS SDK with and without concurrency")
console.log("dateFormat x")
console.log("axisFormat %M:%S")
console.log()
console.log("section Sync")
await sync(client)
console.log()
console.log("section Async")
await async_(client)
console.log("```")
})
async function sync(client: Client) {
const start = millis()
await testX(start, client)
await testY(start, client)
await testZ(start, client)
}
async function async_(client: Client) {
const start = millis()
await Promise.all([
testX(start, client),
testY(start, client),
testZ(start, client),
])
}
async function testX(start: number, client: Client) {
return await run("Test X", start, client)
}
async function testY(start: number, client: Client) {
return await run("Test Y", start, client)
}
async function testZ(start: number, client: Client) {
return await run("Test Z", start, client)
}
async function run(label: string, start: number, client: Client) {
const before = millis() - start
await client.container()
.from("alpine")
.withEnvVariable("NOCACHE", `${label}:${millis()}`)
.withExec(["sh", "-c", "sleep 30"])
.exitCode()
const after = millis() - start
console.log(`${label} : ${before}, ${after}`)
}
function millis() {
return Date.now()
}Not concurrent
async function test(client: Client) {
await testX(client)
await testY(client)
await testZ(client)
}Concurrent
async function test(client: Client) {
await Promise.all([
testX(client),
testY(client),
testZ(client),
])
}
Activity
docs: add concurrency guide
docs: add concurrency guide to cookbook (#5833)
helderco commentedon Oct 12, 2023
#5833 doesn't resolve this since it's just a cookbook.
The point of the guide is for users to understand that concurrency matters, otherwise you can hit a bottleneck pretty easily without realizing. That's the point of the above examples: it takes much longer to execute tasks in sequence when they can run concurrently.
Additionally, the guide can provide resources to learn more about concurrent programming in each language.
TomChv commentedon Oct 16, 2023
@vikram-dagger asked me to transform it into a cookbook, what was missing for it to be a guide?
I could add a more diagrams and resources by I feared that it would be too overwhelming for the users and make it look really complex to add concurrency to Dagger where it's actually something pretty simple. This is why I focused the PR on code example than theoretical explanations.
helderco commentedon Oct 17, 2023
That's the how, what's missing is the why. If users don't reach for concurrency when it makes sense it can be a bottleneck.
docs: add concurrency guide to cookbook (dagger#5833)
docs: add concurrency guide to cookbook (dagger#5833)
docs: add concurrency guide to cookbook (dagger#5833)
docs: add concurrency guide to cookbook (dagger#5833)
docs: add concurrency guide to cookbook (dagger#5833)
[-]📖 Concurrency guide[/-][+]📖 Language concurrency guide[/+][-]📖 Language concurrency guide[/-][+]📖 Multi-language concurrency guide[/+]