# Add Response Compression to a Ktor API

Yes. An agent installs Ktor's Compression plugin, scopes gzip and deflate to JSON responses above a size threshold, tests Accept-Encoding and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-compression/ktor/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the server module first. In a Ktor service like the `postgres` sample in ktorio/ktor-samples, `build.gradle.kts` applies `kotlin("jvm")` and the serialization plugin at `2.4.20` and `io.ktor.plugin` at `3.6.0`, sets `mainClass` to `io.ktor.server.netty.EngineMain`, and depends on `ktor-server-core-jvm`, `ktor-server-content-negotiation-jvm`, `ktor-serialization-kotlinx-json-jvm`, `ktor-server-netty-jvm`, `ktor-server-config-yaml` and the `postgresql` JDBC driver, with `ktor-server-test-host-jvm` and `kotlin-test-junit` for tests and no test source directory. `src/main/resources/application.yaml` names the module `com.example.PostgresApplicationKt.module` on port 8080. `PostgresApplication.kt` calls `configureSerialization()` and `configureRouting(connectToPostgres(embedded = false))`, and `plugins/Routing.kt` serves `POST /articles`, `GET /articles/{id}`, `PUT` and `DELETE`, each answering JSON for an `Article(title, body)`. No response is compressed.

Ktor ships the plugin as its own artifact, so the agent adds `implementation("io.ktor:ktor-server-compression-jvm")` next to the other `io.ktor` lines, with the version supplied by the Ktor Gradle plugin as the rest already are, and writes `plugins/Compression.kt` in the style of `Serialization.kt`: an `Application.configureCompression()` that calls `install(Compression)` with `gzip` and `deflate` encoders, `gzip` at the higher priority, `matchContentType(ContentType.Application.Json)` so only the API's JSON bodies are compressed, and `minimumSize(1024)` so a tiny response is not made larger by the encoding overhead. `module()` calls it first, before serialization and routing, because plugins apply to everything installed after them. The `httpbin` sample in the same repository already depends on `ktor-server-compression` and the `brotli4j` natives, and the pull request points at it as the next step if Brotli is wanted.

One honest finding goes in the description. `ArticleService` creates the table with `TITLE VARCHAR(255)` and `BODY VARCHAR(1024)`, so a single `GET /articles/{id}` response can be at most a little over a kilobyte of JSON and will often sit under the threshold; compression pays off once a list endpoint or longer bodies exist. The agent keeps the threshold rather than lowering it to make the feature look busy, and says so.

Testing has one obstacle: `module()` connects to Postgres through `connectToPostgres`, which reads `postgres.yaml` and opens a JDBC connection at startup, so `testApplication { application { module() } }` cannot run without a database. The agent does not add one. Its `CompressionTest` builds the application from the pieces instead, `configureCompression()`, `configureSerialization()` and a small test route that responds with a list of `Article` values large enough to pass the threshold, then asserts three things with the test client: `Accept-Encoding: gzip` yields `Content-Encoding: gzip` and a body that inflates to the JSON; no `Accept-Encoding` yields no `Content-Encoding`; and a body under the threshold is sent uncompressed even when the client asks. It runs `./gradlew test` with the project's wrapper and pastes the result.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "codex",
  "input": "Add response compression to this Ktor server and open a pull request. Read build.gradle.kts, gradle.properties, src/main/resources/application.yaml, src/main/kotlin/com/example/PostgresApplication.kt, plugins/Routing.kt, plugins/Serialization.kt, models/Article.kt and service/ArticleService.kt first. Add the io.ktor:ktor-server-compression-jvm dependency with the version supplied by the Ktor Gradle plugin, and write plugins/Compression.kt with an Application.configureCompression() that installs Compression with gzip and deflate, gzip at the higher priority, matchContentType for application/json only, and minimumSize of 1024 bytes; call it in module() before the other configure functions. Note in the pull request that the articles table limits title to 255 and body to 1024 characters, so a single article response is usually below the threshold, and do not lower the threshold for that reason. Add a CompressionTest under src/test/kotlin that does not need Postgres: build the application from configureCompression, configureSerialization and a test route returning a list of Article values above the threshold, and assert that Accept-Encoding gzip yields Content-Encoding gzip with a body that inflates to the JSON, that no Accept-Encoding yields no Content-Encoding, and that a response under the threshold is uncompressed. Run ./gradlew test and paste the result. Do not change the routes, the service or the database setup.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request with one added dependency in `build.gradle.kts`, a new `plugins/Compression.kt`, one added call in `PostgresApplication.kt`, and `src/test/kotlin/com/example/CompressionTest.kt`, the first test in the module. The description shows the `./gradlew test` summary from the sandbox with the three cases named, the response headers the test client saw, and the note about the column sizes and the threshold.

The sample has no workflow of its own, so the pasted Gradle output is the check; a service with a CI job that runs `./gradlew test` gets the new test on the pull request. The dependency resolves through the Ktor Gradle plugin's version alignment, so no version string is added.

A reviewer checks that only `application/json` is matched, so a future file download or an already-compressed type is left alone, that a reverse proxy in front of the service is not compressing the same responses a second time, and whether `minimumSize` suits the payloads the real service returns. Then they merge, and clients that send `Accept-Encoding` get smaller responses with no change on their side.

## Run it on every new Ktor service

A team with several Kotlin services sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own module and content types, so a service that already installs `Compression` gets only the missing test, and a service that serves HTML or static files gets the match widened to those types with the reason written down. Each run opens its own pull request.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn ends, with the `session_url` to read the pull request from. The test output is in the session too, so the reviewer sees the headers the test client received before opening the diff.

## Why run it on Rush?

Compression is a plugin install, and whether it is actually doing anything is invisible from the code: it depends on the client's `Accept-Encoding`, the response's content type and its size. In a Rush sandbox the agent runs the server under `testApplication`, sends requests with and without the header and reads `Content-Encoding` back, and every command and its output is kept in the run's record, so the pull request shows what a client will see.

The test design is the transferable part: a module that opens a database connection at startup cannot be tested as a whole without that database, so the agent assembles the application from its configure functions instead. That pattern, and the note about response sizes versus the threshold, carry to the next service unchanged.

## Frequently asked questions

### Why gzip and deflate and not Brotli?

Brotli in Ktor needs the `brotli4j` library and its platform-specific native artifacts, which the `httpbin` sample in the same repository wires up through a custom Gradle component rule. That is a reasonable follow-up, but gzip and deflate need no native code and every HTTP client supports them, so the first pull request stays with those two.

### Will small responses be compressed?

No. `minimumSize(1024)` leaves anything under a kilobyte as it is, because the gzip header and dictionary cost more than they save on a short body. A single article from this schema is often under that, which the pull request says plainly; the threshold earns its keep on lists and longer payloads.

### Does it change Content-Length?

A compressed response is sent chunked, so there is no `Content-Length` header on it, while an uncompressed one keeps the header it has today. The test asserts on `Content-Encoding` and on the inflated body, which is what clients rely on.

### How does the test avoid Postgres?

`module()` calls `connectToPostgres`, which opens a JDBC connection on startup. The test does not call `module()`; it installs `configureCompression()` and `configureSerialization()` directly and adds a route that returns a list of `Article` values, so the plugin is exercised with the same configuration production uses and no database is involved.

### Do clients need to change?

No. Browsers and most HTTP clients send `Accept-Encoding` by default and decompress transparently. A client that does not send the header keeps getting uncompressed JSON, which is the second case the test covers.

## More Ktor jobs

- [Add Connection Pooling to a Ktor Server with HikariCP](https://getrush.ai/run/add-connection-pooling/ktor/)
- [Add CORS and Rate Limiting to a Ktor Server from a Linear Issue](https://getrush.ai/run/add-cors/ktor/)
- [Add Test Coverage to CI for a Ktor App](https://getrush.ai/run/add-coverage-to-ci/ktor/)

## The same job on other stacks

- [Add Response Compression to a Leptos Axum App](https://getrush.ai/run/add-compression/leptos/)
- [Add Response Compression to a Litestar App](https://getrush.ai/run/add-compression/litestar/)
- [Add Response Compression to an Actix Web App from a Linear Issue](https://getrush.ai/run/add-compression/actix/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
