Skip to content

Commit 70a34a3

Browse files
committed
Use exponential backoff when waiting for workflow results
1 parent 2d5d87e commit 70a34a3

File tree

1 file changed

+16
-14
lines changed

1 file changed

+16
-14
lines changed

client/client.go

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"time"
88

99
"github.com/benbjohnson/clock"
10+
"github.com/cenkalti/backoff/v4"
1011
"github.com/cschleiden/go-workflows/backend"
1112
a "github.com/cschleiden/go-workflows/internal/args"
1213
"github.com/cschleiden/go-workflows/internal/converter"
@@ -125,13 +126,21 @@ func (c *client) WaitForWorkflowInstance(ctx context.Context, instance *workflow
125126
timeout = time.Second * 20
126127
}
127128

128-
ticker := c.clock.Ticker(time.Second)
129-
defer ticker.Stop()
129+
b := backoff.ExponentialBackOff{
130+
InitialInterval: time.Millisecond * 1,
131+
MaxInterval: time.Second * 1,
132+
Multiplier: 1.5,
133+
RandomizationFactor: 0.5,
134+
MaxElapsedTime: timeout,
135+
Stop: backoff.Stop,
136+
Clock: c.clock,
137+
}
138+
b.Reset()
130139

131-
ctx, cancel := c.clock.WithTimeout(ctx, timeout)
132-
defer cancel()
140+
ticker := backoff.NewTicker(&b)
141+
defer ticker.Stop()
133142

134-
for {
143+
for range ticker.C {
135144
s, err := c.backend.GetWorkflowInstanceState(ctx, instance)
136145
if err != nil {
137146
return fmt.Errorf("getting workflow state: %w", err)
@@ -140,16 +149,9 @@ func (c *client) WaitForWorkflowInstance(ctx context.Context, instance *workflow
140149
if s == backend.WorkflowStateFinished {
141150
return nil
142151
}
143-
144-
ticker.Reset(time.Second)
145-
select {
146-
case <-ticker.C:
147-
continue
148-
149-
case <-ctx.Done():
150-
return errors.New("workflow did not finish in specified timeout")
151-
}
152152
}
153+
154+
return errors.New("workflow did not finish in specified timeout")
153155
}
154156

155157
// GetWorkflowResult gets the workflow result for the given workflow result. It first waits for the workflow to finish or until

0 commit comments

Comments
 (0)