# Cap jobs running at once

> Let each workspace run at most a few heavy jobs at the same time, and free the slot even when a job crashes.

Say exports are heavy, and you want each customer workspace to run at most 3 at once. The 4th should wait or get a no, and a crashed export mustn’t keep its slot forever.

## 1. Create the limit

* TypeScript

  ```ts
  import { createClient } from "@limitry/sdk";

  // Uses the LIMITRY_API_KEY environment variable.
  const limitry = createClient();

  const limit = await limitry.limits.create({
    name: "Exports at once",
    subject: { kind: "workspace" },
    action: "export",
    amount: 3,
    window: "concurrent",
  });
  console.log(limit.id);
  ```

* Python

  ```python
  from limitry import Limitry

  # Uses the LIMITRY_API_KEY environment variable.
  limitry = Limitry()

  limit = limitry.limits.create(
      name="Exports at once",
      subject={"kind": "workspace"},
      action="export",
      amount=3,
      window="concurrent",
  )
  print(limit.id)
  ```

* CLI

  ```bash
  limitry limits create --name "Exports at once" --subject '{"kind":"workspace"}' \
    --action export --amount 3 --window concurrent
  ```

* curl

  ```bash
  curl -X POST https://api.limitry.com/v1/limits \
    -H "Authorization: Bearer $LIMITRY_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"name":"Exports at once","subject":{"kind":"workspace"},"action":"export",
         "amount":3,"window":"concurrent"}'
  ```

## 2. Take a slot for the job

`reserve` takes a slot before the job starts and gives it back when the job ends, whether it succeeds or throws:

* TypeScript

  ```ts
  import { LimitReachedError } from "@limitry/sdk";

  try {
    await limitry.reserve(
      {
        subject: { kind: "workspace", id: workspaceId },
        action: "export",
        ttlSeconds: 600,
      },
      async (reservation) => {
        for (const chunk of chunks) {
          await exportChunk(chunk);
          await reservation.extend(600); // still running: keep the slot for 600 s from now
        }
      },
    );
  } catch (err) {
    if (err instanceof LimitReachedError) {
      // All 3 slots are taken. Try again in err.retryAfterSeconds.
      return requeue(job, err.retryAfterSeconds);
    }
    throw err;
  }
  ```

* Python

  ```python
  from limitry import LimitReachedError

  try:
      with limitry.reserve(
          subject={"kind": "workspace", "id": workspace_id},
          action="export",
          ttl_seconds=600,
      ) as reservation:
          for chunk in chunks:
              export_chunk(chunk)
              reservation.extend(600)  # still running: keep the slot for 600 s from now
  except LimitReachedError as err:
      # All 3 slots are taken. Try again in err.retry_after_seconds.
      requeue(job, err.retry_after_seconds)
  ```

## 3. If the worker dies

A slot is a reservation, and it lasts `ttlSeconds`. A job that’s still running extends it as it goes. A worker that crashes stops extending, and the slot frees itself within `ttlSeconds`. Pick a `ttlSeconds` comfortably longer than the gap between your `extend` calls. An `extend()` with no argument keeps the slot for 300 seconds from the call. Pass a number of seconds to keep it longer.

## Combine with a daily limit

A concurrency limit doesn’t count use. To also cap exports per day, add a second limit on the same action with the window `day`. The `reserve` above then has to fit both.

Related: [Rolling windows and concurrency](/docs/rolling-and-concurrency/), [Reservations](/docs/reservations/).
