Model Layering and Prefix Cache Optimization for Long-Horizon Coding Agents

    Long-horizon coding agents rack up cost and can drift off course as context grows. This article covers stable prompt prefixes for cache hits, reasoning-effort tiers, controller–worker orchestration, correction-ability evaluation, and a simple cost formula.

    Two Core Problems in Long-Horizon Coding

    Long-horizon coding agents run for tens or hundreds of turns: they read code, edit multiple files, run tests, and iterate. Unlike one-shot Q&A, each turn re-injects history, tool results, and code snippets. Longer tasks mean larger inputs, higher cost, and more latency.

    Teams typically hit two issues.

    Cost blowups. Input tokens are billed every turn. If the prompt structure is unstable, even nearly identical content may miss server-side prefix cache, and a single task can cost far more than expected.

    Directional drift. After a bad early assumption, the agent may keep editing six or more files until tests fail. Rework is then most expensive. A coding agent should be judged not only on first-pass correctness, but on how quickly it recovers when corrected mid-run.

    The rest of this article covers cache design, reasoning-effort choice, controller–worker orchestration, correction evaluation, and cost accounting.

    Keep Prompt Prefixes Stable

    How prefix cache works

    Most LLM APIs support prefix caching. The server caches a contiguous prefix of the request. Later requests that start with the same bytes can read that prefix at a lower rate instead of recomputing it. Cache-read prices are usually much cheaper than standard input, so this is a primary lever for long-horizon cost.

    The prefix must match exactly. One changed character invalidates everything after it.

    Common cache-busting mistakes

    These all break prefix cache:

    • Dynamic fields in system instructions (timestamps, request IDs).
    • Reordering, adding, or removing tools each turn.
    • Putting project rules or current file contents before system instructions.
    • Rewording top-level instructions, including punctuation or whitespace.

    These are easy to miss in debugging. Treat the static prompt as an API contract: review changes and version them.

    Put static content first, dynamic content last.

    1. def build_request(system_prompt, tool_schemas, project_rules, history, current_task):
    2. # Static prefix: byte-identical every turn
    3. static_prefix = [
    4. {"role": "system", "content": system_prompt},
    5. {"role": "system", "content": project_rules},
    6. {"role": "system", "content": tool_schemas},
    7. ]
    8. # Dynamic suffix: history and current task
    9. dynamic_suffix = history + [{"role": "user", "content": current_task}]
    10. return static_prefix + dynamic_suffix

    Serialize tool definitions in a fixed order (for example, sort by name). Version project rules; change the prefix only when the version changes.

    Choose Reasoning Effort by Task Difficulty

    Many models expose a reasoning-effort (or similar) knob that trades speed, cost, and depth. Higher effort means more thinking tokens before the answer, plus higher latency and cost.

    A practical split:

    • Formatting, renaming, simple style: low.
    • Typical feature work and unit tests: medium.
    • Architecture, cross-module bugs, concurrency: high.

    Example config:

    1. agent:
    2. controller:
    3. reasoning_effort: high # task breakdown and change review
    4. workers:
    5. reasoning_effort: low # search, style, tests, and other execution

    Names and number of tiers depend on the provider. Validate on your eval set rather than generic intuition.

    Controller–Worker Orchestration

    Design

    A stronger controller model:

    1. Understands the request and splits it into independent subtasks.
    2. Orders subtasks by dependencies.
    3. Collects results, reviews diffs, and decides whether to merge.

    Lighter workers do bounded actions: symbol search, style edits, unit tests. These need less judgment and can run concurrently on cheaper, faster models.

    Expensive reasoning stays on decisions; bulk read-and-try work goes to cheap models.

    Pseudocode

    1. def run_task(task, controller, workers):
    2. plan = controller.plan(task) # subtasks and dependencies
    3. results = []
    4. for batch in plan.topological_batches():
    5. # Independent subtasks in a batch can run concurrently
    6. futures = [workers.submit(sub) for sub in batch]
    7. results.extend(f.result() for f in futures)
    8. diff = collect_diff(results)
    9. review = controller.review(diff, task)
    10. if review.approved:
    11. apply_diff(diff)
    12. else:
    13. return controller.replan(task, review.feedback)

    Risks

    • Write conflicts: two workers edit the same file. Partition write rights by file or module; one writer per file.
    • Missing context: workers only see the subtask. The controller should attach relevant API contracts and style rules.
    • Untrusted output: the controller must review, and tests must pass. Do not merge because a worker said “done.”

    Evaluating Course Correction

    Why a separate eval

    Long-horizon agents rarely get everything right first try. People add requirements, fix assumptions, or reject a direction. How well the agent absorbs that correction determines rework.

    One-shot pass rate hides this.

    A reproducible method

    Build multi-step tasks, inject a requirement change mid-run, and record:

    • Whether correct work is kept or everything is restarted.
    • Turns from injection until the agent is back on track.
    • Files edited on the wrong path and later reverted.
    • Final test pass rate and total tokens.

    Cover multiple modules and difficulties. Pin prompt version, reasoning effort, and tool set so runs are comparable.

    Cost Formula

    Separate cache hits, uncached input, and output:

    Total cost = cached tokens × cache-read price + uncached input tokens × input price + output tokens × output price

    1. def estimate_cost(cached_tokens, uncached_input, output_tokens, prices):
    2. """prices are per million tokens from the provider's official list."""
    3. return (
    4. cached_tokens * prices["cache_read"]
    5. + uncached_input * prices["input"]
    6. + output_tokens * prices["output"]
    7. ) / 1_000_000

    Notes:

    1. Prices vary; use the official price list, not numbers from elsewhere.
    2. Long-horizon input usually dwarfs output; cache hit rate dominates cost. Raising hit rate often beats a small unit-price cut.
    3. Orchestration adds calls. Account for controller vs. worker spend and check that speed gains beat extra call cost.

    Rollout Checklist

    • Static prompts versioned; changes reviewed.
    • Tools serialized in a fixed order.
    • All dynamic content after the static prefix.
    • Tasks tiered by difficulty with matching reasoning effort.
    • Concurrent writes partitioned at file level.
    • Controller review backed by tests, not model judgment alone.
    • Regular correction-ability evals.
    • Cost reports split cache hits, uncached input, and output.

    Summary

    Cost and stability of long-horizon coding agents depend as much on engineering as on the model. Stable prefixes raise cache hits. Effort tiers avoid wasting compute on simple work. Controller–worker design keeps strong models on decisions and cheap models on I/O. Correction evals catch drift before it becomes expensive rework.

    Start with prefix stability and cost accounting—low effort, fast payoff. Then add effort tiers and concurrent orchestration, and validate each step on a fixed eval set.