Skip to content

Project Brief: Job Runner

The Course
•
15 min study

Today's project is a concurrent job runner. It reads jobs, runs them through a pool of workers on a bounded queue, retries transient failures with backoff, applies timeouts, and supports cancellation. Every day of this course shows up in it.

The input

Each line holds an id, a kind and an argument. Lines that don't parse, and ids already used, count as rejected.

LineJob
1 sum 1,2,3Adds whole numbers
2 upper hello worldConverts the rest of the line to capitals
3 flaky 2Fails with a transient error twice, then succeeds
4 slow 50Waits that many milliseconds

The rules

  • Two workers read from a bounded queue of 4, so a large input can't outrun them.
  • Transient failures retry up to 3 attempts, with delays of 10 ms, then 20 ms.
  • Each attempt has a timeout of 200 ms in the sample program. A timeout is final. This differs from the Day 3 retry helper, which treated a timeout as transient, and it's a deliberate choice: these jobs run on this machine, so a job that hit its timeout once will very likely hit it again, and retrying would only hold a worker for three times as long. A timeout on a network call, where a slow server may recover, is still a good reason to retry. Decide per kind of work, and write the choice down as a rule like this one.
  • Any other exception fails the job at once, without a retry.
  • After cancellation, jobs not yet started report Cancelled with 0 attempts, and their handler isn't called.

The invariants

An invariant is something that must always be true. Concurrency makes these more useful than examples, since you can't predict the exact order.

  1. Each job produces exactly one outcome. This holds even on cancellation. No job vanishes.
  2. At most Workers handlers run at once.
  3. The input is read no further than the queue allows.
  4. A failing input reaches the caller, rather than hanging.

Which test would catch a violation of each? You'll compare your thoughts with the real checks in lesson 3.

Where the ideas live

FileJobDays
Jobs.csJob and Outcome hierarchies, and parsing1 and 2
Handlers.csIDelayer, IJobHandler, the standard handler3 and 6
Runner.csChannels, workers, retries, timeouts3, 4 and 6
Program.csThe composition root and report6
Checks.csFakes, gates and properties6

Trace the retries

Predict the attempts and delays for a job that fails twice with a limit of 3, and then for one that fails forever. The attempt >= maxAttempts line is where most off-by-one mistakes hide.

Attempts and delays C#
Trace(2, 3);
Trace(9, 3);
Trace(0, 1);

static void Trace(int failuresFirst, int maxAttempts)
{
    var delays = new List<int>();
    for (int attempt = 1; ; attempt++)
    {
        bool failed = attempt <= failuresFirst;
        if (!failed)
        {
            Console.WriteLine($"succeeded on {attempt}, delays [{string.Join(",", delays)}]");
            return;
        }
        if (attempt >= maxAttempts)
        {
            Console.WriteLine($"gave up on {attempt}, delays [{string.Join(",", delays)}]");
            return;
        }
        delays.Add(10 * (int)Math.Pow(2, attempt - 1));
    }
}
Check your prediction
Text
succeeded on 3, delays [10,20]
gave up on 3, delays [10,20]
succeeded on 1, delays []

Trace the capacity

With one blocked worker and a queue of 2, how many jobs has the producer pulled from its input? It's the same arithmetic as on Day 4: one being handled, the queue's capacity, and one waiting to be written.

The arithmetic of a full pipeline C#
foreach ((int workers, int capacity) in new[] { (1, 2), (2, 4), (4, 1) })
{
    Console.WriteLine($"{workers} workers, capacity {capacity}: at most {workers + capacity + 1} pulled");
}
Check your prediction
Text
1 workers, capacity 2: at most 4 pulled
2 workers, capacity 4: at most 7 pulled
4 workers, capacity 1: at most 6 pulled

Your turn

Exercise

Parse a job

Using a small hierarchy, write Parse(string line), which handles sum and upper and returns null for anything else. An id must be a whole number of at least 1, sum requires comma-separated whole numbers, and upper keeps the spaces in its text. Print the results for 1 sum 1,2, 2 upper two words, 0 upper x, 3 sum 1,x and 4 nope x.

When it works, it prints the lines below. Each Name { … } line is a record's built-in ToString, so print the record itself rather than formatting it:

Text
SumJob { Id = 1, Total = 3 }
UpperJob { Id = 2, Text = two words }
rejected
rejected
rejected
Your workspace C#
#nullable enable

string line = "2 upper two words";
Console.WriteLine(line.Split(' ', 3).Length);
Hint 1: the idea

Split into three parts at most, so the argument keeps its spaces. Then a switch on the second part picks the kind.

Hint 2: a first step

Handle upper first, since it has no argument parsing. Put the sum parsing in its own helper, which returns null if any number is bad.

Show one solution
C#
#nullable enable

foreach (string line in new[] { "1 sum 1,2", "2 upper two words", "0 upper x", "3 sum 1,x", "4 nope x" })
{
    Console.WriteLine(Parse(line)?.ToString() ?? "rejected");
}

static Job? Parse(string line)
{
    string[] parts = line.Split(' ', 3);
    if (parts.Length != 3 || !int.TryParse(parts[0], out int id) || id < 1)
    {
        return null;
    }
    return parts[1] switch
    {
        "upper" => new UpperJob(id, parts[2]),
        "sum" => ParseSum(id, parts[2]),
        _ => null,
    };
}

static SumJob? ParseSum(int id, string text)
{
    int total = 0;
    foreach (string piece in text.Split(','))
    {
        if (!int.TryParse(piece, out int value))
        {
            return null;
        }
        total += value;
    }
    return new SumJob(id, total);
}

abstract record Job(int Id);

sealed record SumJob(int Id, int Total) : Job(Id);

sealed record UpperJob(int Id, string Text) : Job(Id);
Text
SumJob { Id = 1, Total = 3 }
UpperJob { Id = 2, Text = two words }
rejected
rejected
rejected

Was this article helpful?

Your response is saved on this device.