# A ten minute wait should not cost you Lambda time

> The goodnight routine needed to pause in the middle. That single requirement is what moved it out of Lambda and into Step Functions.

- Author: Deyan Peev (https://deyanpeev.com)
- Published: 2021-08-28
- Tags: AWS, Step Functions, Lambda, Serverless, Python
- URL: https://deyanpeev.com/posts/a-ten-minute-wait-should-not-cost-lambda-time

"Alexa, goodnight" should do five things: lock the front door, dim whatever is
still on, drop the heating to the night setpoint, wait long enough for me to
get from the sofa to the bedroom, and then switch everything off.

Four of those are a loop over some devices. The fifth is a ten minute pause,
and that pause is why this isn't a Lambda function.

# What the pause costs

The naive version is `time.sleep(600)` in the middle of a handler. A few things
are wrong with that, roughly in increasing order of how much they matter.

You pay for it. Lambda bills wall time, and ten minutes of a 256 MB function
doing nothing is ten minutes of a 256 MB function. Fractions of a cent, sure,
but still absurd.

You also can't, or not for long. The maximum timeout is fifteen minutes, so a
ten minute wait fits (barely) and leaves no room for the routine to grow. The
moment I wanted a twenty minute version for guests the design was finished.

And a retry replays all of it. If the function dies at minute nine, whatever
invoked it retries from the top, so it locks a locked door, dims the lights
again and waits another ten minutes. Nothing here is dangerous to repeat, but
that's luck, I didn't design it that way.

# What a Wait state costs

Nothing. In Step Functions a `Wait` is a state, and you're billed per state
transition, not per second of waiting.

```json
"GracePeriod": {
  "Type": "Wait",
  "Seconds": 600,
  "Comment": "Long enough to get from the sofa to the bedroom",
  "Next": "LightsOut"
}
```

The goodnight routine is six states in total, and the execution history in the
console shows which one a run is sitting in. That's the feature I use most. A
routine that looks stuck at eleven at night is almost always the wait, and now
I can see that instead of guessing.

# One function, many tasks

Each task state points at the same Lambda function and passes it a name:

```json
"LockUp": {
  "Type": "Task",
  "Resource": "${RoutineTaskFunctionArn}",
  "Parameters": {
    "task": "lock_doors",
    "arguments": {}
  },
  "Retry": [
    {
      "ErrorEquals": ["Lambda.ServiceException", "Lambda.TooManyRequestsException"],
      "IntervalSeconds": 2,
      "MaxAttempts": 3,
      "BackoffRate": 2
    }
  ],
  "ResultPath": "$.lockUp",
  "Next": "DimLights"
}
```

On the Python side that's a dictionary and a lookup:

```python
TASKS = {
    "lock_doors": lock_doors,
    "dim_lights": dim_lights,
    "lights_off": lights_off,
    "set_setpoint": set_setpoint,
    "set_mode": set_mode,
    "notify": notify,
}


def lambda_handler(event, context):
    name = event.get("task")
    if name not in TASKS:
        raise errors.UnsupportedOperation("unknown routine task {0}".format(name))
    return TASKS[name](event.get("arguments", {}))
```

Six functions would have meant six deployment packages, six roles and six sets
of environment variables, for six things that all talk to the same two tables.
One function with a task key is less to own. The trade is that they all share
a timeout and a memory setting. I haven't hit a case yet where that matters.

It also helps that the retry policy lives in the state machine and not in the
code. The lock is the flaky one (it sits behind a bridge that reboots itself
now and then), and giving it two attempts five seconds apart is a four-line
edit to a JSON file. No Python changes.

# The away version, and a Choice state

The same machinery shuts the flat down when everybody leaves, with one
difference at the front:

```json
"StillOccupied?": {
  "Type": "Choice",
  "Choices": [{ "Variable": "$.occupants", "IsPresent": true, "Next": "Cancelled" }],
  "Default": "ShutDown"
}
```

Phones cross the geofence in a ragged way. Somebody walks to the corner shop,
the geofence fires, and thirty seconds later they're back. With the check in
the state machine instead of the trigger, the routine can be started
optimistically and then change its mind. The console shows a run that ended at
`Cancelled` - and I'd much sooner find that than no run at all.

# What it does not solve

Step Functions has its own rough edges. The state machine definition wants the
task function's ARN, and that means a substitution at deploy time, so both my
SAM template and my Pulumi program grew a small piece of machinery to inject
it. And ASL is JSON, so a typo in a state name is a deploy-time error at best
and a runtime one at worst.

I'd still pick it again. Once a workflow has a pause in it, or a branch, or a
step that should be retried differently from its neighbours, the question is
which of those you want to write yourself. I didn't want to write the pause.
