---
title: "Prevent two workers from claiming the same LLM job in C#"
url: https://recursiveai.org/onellm/cookbook/lease-agent-work-with-onelite/
description: "Prevent two C# workers from claiming the same LLM job. Take a OneLite lease on a shared job ID and reclaim it after the first worker exits."
version: "1.0.1"
---

# Prevent two workers from claiming the same LLM job in C#

**OneLLM** is a free, open-source LLM and agent library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneLlm.OneLite) · [GitHub](https://github.com/recursive-ai-oss/onellm-csharp) · [Docs](https://recursiveai.org/onellm/docs/) · [Download example (.zip)](https://recursiveai.org/onellm/cookbook/lease-agent-work-with-onelite/lease-agent-work-with-onelite.zip)

Take a lease, or a claim with an expiry time, in a shared OneLite file. OneLite is Recursive AI’s embedded SQLite-compatible database; the job ID is the instance ID in the API.

```shell
dotnet add package RecursiveAI.OneLlm.OneLite
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using OneLlm.Instances;
using OneLlm.OneLite;

using var db = await OneLiteStorage
    .OpenAsync("jobs.db");
var store = await OneLiteInstanceStore
    .CreateAsync(db);
await using var workerA =
    await store.AcquireAsync("job-42");
try
{
    await using var workerB =
        await store.AcquireAsync("job-42");
    throw new Exception("Both claimed the job.");
}
catch (InstanceLockedException)
{
    Console.WriteLine("Worker B was blocked");
}
```

Unzip [the example](https://recursiveai.org/onellm/cookbook/lease-agent-work-with-onelite/lease-agent-work-with-onelite.zip), then `dotnet run`.

Creates `jobs.db` locally. The two claims for `job-42` are in the code; no model or input file is needed. Prints:

```text
Worker B was blocked
```

## The full program

The download runs two separate workers against the same file. Worker A takes the lease in a child process. Worker B is blocked, stops the child without releasing its lease, then claims the same job ID after the lease expires.

```csharp
using System.Diagnostics;
using RecursiveAI.OneLite;
using OneLlm.Instances;
using OneLlm.OneLite;

const string job = "job-42";
string path = Path.GetFullPath("jobs.db");
using var db = await OneLiteStorage.OpenAsync(path);
var store = await OneLiteInstanceStore.CreateAsync(db,
    leaseDuration: TimeSpan.FromSeconds(6));

if (args is ["hold"])
{
    await using var lease = await store.AcquireAsync(job);
    Console.WriteLine("Worker A claimed job-42");
    await Task.Delay(Timeout.Infinite);
    return;
}

var start = new ProcessStartInfo(
    Environment.ProcessPath ?? throw new InvalidOperationException())
{
    UseShellExecute = false,
    RedirectStandardOutput = true
};
start.ArgumentList.Add("hold");
using var worker = Process.Start(start)
    ?? throw new InvalidOperationException("Could not start worker A.");
try
{
    Console.WriteLine(await worker.StandardOutput.ReadLineAsync()
        .WaitAsync(TimeSpan.FromSeconds(15))
        ?? throw new InvalidOperationException("Worker A exited."));

    try
    {
        await using var refused = await store.AcquireAsync(job);
        throw new InvalidOperationException("Two claims succeeded.");
    }
    catch (InstanceLockedException)
    {
        Console.WriteLine("Worker B was blocked");
    }
}
finally
{
    if (!worker.HasExited)
        worker.Kill(); // No lease disposal: simulate a crash.
    await worker.WaitForExitAsync();
}

// Wait until any renewal from A has expired.
await Task.Delay(TimeSpan.FromSeconds(7));
await using var recovered = await store.AcquireAsync(job);
Console.WriteLine("Worker B claimed the expired lease");
```

`dotnet run` prints:

```text
Worker A claimed job-42
Worker B was blocked
Worker B claimed the expired lease
```

When `AcquireAsync` throws `InstanceLockedException`, the caller didn’t claim the job and shouldn’t start work on it. Use the same path and job ID in both workers: two separate database files don’t coordinate claims.

## Variations

**Release on normal completion.** Replace the code after `CreateAsync` in the snippet at the top. Disposing the lease makes the job claimable without waiting for expiry.

```csharp
await using (var first = await store.AcquireAsync("job-42"))
    Console.WriteLine("Worker A claimed job-42");

await using var next = await store.AcquireAsync("job-42");
Console.WriteLine("Worker B claimed the released lease");
```

```text
Worker A claimed job-42
Worker B claimed the released lease
```

## Related recipes

- [Cache LLM responses](https://recursiveai.org/onellm/cookbook/cache-llm-responses/)
- [Save and resume a chat](https://recursiveai.org/onellm/cookbook/save-and-resume-a-chat/)

## The short answer

Make the claim a single store operation keyed by the job ID. With `OneLiteInstanceStore`, call `AcquireAsync(id)` and only start work if it returns a lease. Hold the lease with `await using`. On an ordinary exit it’s released; if the process dies, its renewals stop and the next worker can take over after expiry.

## How do you stop two workers from picking the same job?

A check followed by a separate write leaves time for another worker to make the same check. In OneLite the claim uses a single write transaction: the store inserts the lease row or replaces it if the old lease has expired. If the transaction didn’t take the row, the caller gets `InstanceLockedException`. The transaction isn’t held open while the job runs; the committed row represents the claim.

That only helps if both workers claim the **same job ID**. Assign it when you identify the job and carry it through retries; don’t generate a new job ID each time you call `AcquireAsync`. The lease is also separate from a job queue: your app chooses what to process and records when it’s finished. Acquiring a lease successfully isn’t evidence the job was never run before.

## What happens to a lease when a worker crashes?

[OneLLM’s database stores](https://recursiveai.org/onellm/docs/stores/#leases-that-survive-crashes) default to a 60-second lease and renew it every third of the lease duration while held. The example uses a shorter window to demonstrate recovery. The waiting period runs from the most recent renewal, not the start of the job. If you try again too soon, the stored lease can still be valid even though its old process is gone.

## Does a database lock guarantee exactly-once external actions?

No. An expired lease doesn’t cancel a paused worker or roll back a request it already sent. For example, if a worker sends a notification and dies before saving that it sent it, a replacement can acquire the lease and still send a duplicate. For operations where duplicate effects matter, check the last durable result before retrying and use a stable idempotency key where the destination supports one. [This guide to idempotent APIs](https://aws.amazon.com/builders-library/making-retries-safe-with-idempotent-APIs/) explains how request identifiers make retries safer.
