# Apply backpressure to Ktor background work with a bounded coroutine channel

Launching one detached coroutine per incoming request lets traffic outrun a slow downstream service. A finite channel bounds pending work; trySend tells the route when it must return an overload response. A lifecycle-owned scope keeps the worker attached to application shutdown.

Save this requirement in Perch and check it after each agent edit. The rule gives your agent a named check to run, a finding to repair, and the same command to recheck.

## Implement the Ktor boundary

Save this illustrative integration module as `src/main/kotlin/example/ReceiptQueue.kt`.

```kotlin
package example
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.async

data class ReceiptJob(val orderId: Long, val tenantId: String)

class ReceiptQueue(scope: CoroutineScope, send: suspend (ReceiptJob) -> Unit) {
    private val jobs = Channel<ReceiptJob>(capacity = 64)
    private val worker = scope.async {
        for (job in jobs) send(job)
    }
    fun offer(job: ReceiptJob): Boolean = jobs.trySend(job).isSuccess
    suspend fun close() {
        jobs.close()
        worker.await()
    }
}
```

The order, inventory, or resource-lifetime scenario is adapted from Perch’s public [order-service source at commit 4af67af](https://github.com/lakeday-org/perch/blob/4af67af46d76ac99398d61c7ad0a45441760d4dc/test/fixtures/order-service/checkout.py). This Ktor implementation is an illustrative adaptation.

## Integrate with your application

Create the queue from an application-owned CoroutineScope and close it on Ktor shutdown. Construct ReceiptJob from verified identity and immutable order data; do not retain ApplicationCall in the worker. Return 202 only when offer succeeds and an overload status when it fails. Catch per-job delivery errors under an explicit retry/dead-letter policy; the worker uses async/await so draining shutdown observes its failure; configure supervisor ownership and a finite shutdown timeout explicitly. An in-memory channel loses queued jobs on process failure: use a durable queue or outbox when delivery matters.



## Exercise the boundary and failure paths

| Scenario | Expected outcome |
| --- | --- |
| Queue has capacity | Job accepted |
| 64 pending jobs and blocked worker | Next offer returns false |
| Shutdown requested | Channel closes and worker is joined |
| Delivery throws | Failure is observable; retry policy decides recovery |

Add regression tests for these cases in your existing Ktor test project. Use separate connections or deliberately reordered completion where the case involves concurrency; a sequential happy-path test does not exercise that failure. Run the test command after creating the matching test file or suite:

```sh
./gradlew test --tests example.ReceiptQueueTest
```

The scenarios above specify tests to implement. A completed Perch source check below is separate from running these application integration tests.

## Introduce the specific agent regression

In a throwaway copy, replace this source span:

```kotlin
Channel<ReceiptJob>(capacity = 64)
```

with:

```kotlin
Channel<ReceiptJob>(capacity = Channel.UNLIMITED)
```

Run the relevant negative test and the Perch command on that broken copy. Restore the corrected source before committing the application. The supplied mutation reproduces the exact regression for the rule check.

## Preserve the requirement as a Perch rule

Save this in `.perch/rules/perch-guide-ktor-bounded-request-worker.yaml` at the repository root, keeping your existing `perch.yaml`:

```yaml
- name: receipt-queue-bounded
  where: "src/main/kotlin/example/ReceiptQueue.kt"
  ensure: >-
    The ReceiptJob channel must have a finite capacity, not Channel.UNLIMITED, so overload is rejected rather than retained without bound.
```

Install and authenticate the CLI once, then check the current working file:

```sh
npm install -g @lakeday/perch
perch login
perch check src/main/kotlin/example/ReceiptQueue.kt --rules receipt-queue-bounded --json
```

Use Node 22 or newer. The framework can use another language; Perch’s CLI remains a Node command. A gated finding exits 3. Exits 1 or 2 mean the check did not complete and must be reported as a blocker.

## Inspect the captured rule check

On 2026-10-14, Perch using jev-latest checked the exact fixed and broken source provided here. The capture records SHA-256 hashes of both sources and the requirement.

| Source control | Exit | Outcome |
| --- | --- | --- |
| Broken | 3 | Rule finding |
| Corrected | 0 | No rule finding |

The rule distinguished these controls in this run. [Raw Perch capture](/bounded-request-worker/capture.json) · [Exact sources and mutation](/bounded-request-worker/source.json).

## Install the rule pack and configure your agent

[Download this rule pack ZIP](/bounded-request-worker/rule-pack.zip) · [Download the YAML rules](/bounded-request-worker/rules.yaml) · [Agent task](/bounded-request-worker/agent-task.txt). The pack contains the rule, its example paths and the repair/recheck instructions. Review the `where` selector before using it in an existing project. Keep your root `perch.yaml`; install this rule as a separate file under `.perch/rules/`.

1. Install Perch using Node 22 or newer and sign in once:

```sh
npm install -g @lakeday/perch
perch login
```

2. Download the pack, inspect it, and extract it from your repository root. The extraction preserves any existing files:

```sh
curl -fL 'https://reporules.fyi/ktor/bounded-request-worker/rule-pack.zip' -o 'perch-guide-ktor-bounded-request-worker.zip'
unzip -n 'perch-guide-ktor-bounded-request-worker.zip'
```

The installed rule is `.perch/rules/perch-guide-ktor-bounded-request-worker.yaml`. Its selector matches `src/main/kotlin/example/ReceiptQueue.kt` in this example; adapt the selector to your application file before checking an existing project.

3. Configure the coding agent you use. Run one of these commands:

Claude Code:

```sh
perch setup claude-code
```

Codex:

```sh
perch setup codex
```

Cursor:

```sh
perch setup cursor
```

Pi:

```sh
perch setup pi
```

4. Ask the agent to edit the implementation and check the saved requirement:

> Use the installed Perch skill while editing src/main/kotlin/example/ReceiptQueue.kt. Preserve receipt-queue-bounded. Run perch check src/main/kotlin/example/ReceiptQueue.kt --rules receipt-queue-bounded --json after the edit. Read each finding and the affected code, fix the implementation, and run the identical check again after the fix. Keep the rule and regression tests intact. Run the application's relevant regression tests and report the commands and actual results. Exit 3 means a rule finding; exit 1 or 2 means the check did not complete. Report an unavailable or incomplete check as blocked. Do not claim the application tests ran if only the Perch check ran.

5. After repairing a finding, run the same check again and inspect the result:

```sh
perch check src/main/kotlin/example/ReceiptQueue.kt --rules receipt-queue-bounded --json
```

Commit the downloaded rule and the installed agent configuration with your application. The rule file adds no guarantee of correctness; keep the regression tests from this guide.

With the base reference fetched, use `perch scan --since origin/main --filter type=lint` in CI.

## Framework references and verification scope

- [kotlinlang.org reference](https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/-channel/)

The dated capture records the source check shown above. Implement the adapters, schema and regression tests described in this guide in your application. Unchanged requests reuse cached answers; fresh model judgments can vary. Model analysis sends relevant source to the configured service.
