# Add Connection Pooling to a Ktor Server with HikariCP

Yes. An agent replaces a Ktor server's single shared JDBC connection with a HikariCP pool from config, tests it under concurrent requests, and opens a pull request.

[Run this on Rush](https://cloud.getrush.ai/run/add-connection-pooling/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 in its own sandbox before it changes it. In a service like the `postgres` sample in ktorio/ktor-samples, `build.gradle.kts` applies Kotlin 2.4.20, the Ktor plugin 3.6.0 and the serialization plugin, sets `mainClass` to `io.ktor.server.netty.EngineMain`, pins `jvmToolchain(17)`, 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`, Logback 1.5.21 and `org.postgresql:postgresql` 42.7.8, with `ktor-server-test-host-jvm` and `kotlin-test-junit` for tests that do not yet exist. A `databaseInstance` task shells out to `docker-compose up`, and `docker-compose.yaml` runs `postgres:18.0-alpine` on port 5432 with the user, password and database named in `postgres.yaml`.

The problem is in `src/main/kotlin/com/example/plugins/Routing.kt`. `connectToPostgres` calls `Class.forName("org.postgresql.Driver")` and `DriverManager.getConnection` once, reading the database name, user and password out of `postgres.yaml` with `YamlConfig`, and returns one `java.sql.Connection`. `PostgresApplication.kt` hands that connection to `ArticleService`, which creates the `articles` table in its `init` block and then runs every `create`, `read`, `update` and `delete` on the same connection inside `withContext(Dispatchers.IO)`. A JDBC connection is not meant to be used from several threads at once, so two overlapping requests share one statement pipeline, and if the database restarts the connection is dead for the life of the process. The `embedded` branch of `connectToPostgres` builds a URL with an H2-style `DB_CLOSE_DELAY` parameter that the Postgres driver does not read.

The fix follows a pattern already in the repository: the `h2` sample depends on `com.zaxxer:HikariCP` 7.0.2 and builds a `HikariDataSource` from a `HikariConfig` in `H2.kt`. The agent adds the same dependency to the `postgres` sample's `build.gradle.kts`, writes `plugins/Database.kt` with a `configureDatabase()` extension that reads `db.jdbcUrl`, `db.username`, `db.password` and `db.maximumPoolSize` from `application.yaml` through `environment.config`, builds the pool, and closes it on the `ApplicationStopping` event so a shutdown returns connections cleanly. `application.yaml` gains a `db` block whose values default to the ones in `postgres.yaml` and can be overridden with environment variables through Ktor's `$VAR` syntax. `ArticleService` takes a `DataSource` instead of a `Connection`, and each method borrows a connection with `dataSource.connection.use { }` so it goes back to the pool when the block ends; the table creation in `init` does the same. `connectToPostgres` and its unused `embedded` branch are removed, and `PostgresApplication.kt` calls `configureDatabase()` before `configureRouting`.

The tests are the proof that was missing. `ArticleServiceTest` opens a pool against the Docker Postgres, launches many `create` calls at once with `coroutineScope` and `launch`, and asserts that every call returns a distinct id and that each article reads back with its own title, which a single shared connection cannot be trusted to do. `RoutingTest` uses `testApplication` with the same pool to walk `POST /articles`, `GET /articles/{id}`, `PUT` and `DELETE`, and checks the `404` and `400` answers the routes already define. The agent starts the database with `docker compose up -d`, runs `./gradlew test`, starts the server with `./gradlew run`, sends overlapping requests with `curl` in a loop, and pastes the test report summary and the pool's startup log line in the pull request.

## Start it with one API call

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

```json
{
  "agent": "codex",
  "input": "Replace the single shared JDBC connection in this Ktor server with a HikariCP connection pool and open a pull request. Read build.gradle.kts, gradle.properties, settings.gradle.kts, docker-compose.yaml, postgres.yaml, README.md, src/main/resources/application.yaml, src/main/resources/logback.xml and every file under src/main/kotlin first, and look at how the h2 sample in this repository builds a HikariDataSource. Add com.zaxxer:HikariCP at the version the h2 sample uses. Add plugins/Database.kt with a configureDatabase() function that reads db.jdbcUrl, db.username, db.password and db.maximumPoolSize from application.yaml, defaulting to the values in postgres.yaml and overridable by environment variables, builds the pool, and closes it on ApplicationStopping. Change ArticleService to take a DataSource and borrow a connection per call with use, including the table creation. Remove connectToPostgres and its embedded branch. Add ArticleServiceTest that creates many articles concurrently against the Docker Postgres and asserts distinct ids and correct reads, and RoutingTest with testApplication covering create, read, update, delete and the 404 and 400 paths. Update README.md for the new config. Start the database with docker compose, run ./gradlew test and ./gradlew run, send overlapping requests with curl, and paste the test summary in the pull request. Do not change the routes' paths or status codes.",
  "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 on its own branch that changes `build.gradle.kts`, `application.yaml`, `README.md`, `PostgresApplication.kt`, `plugins/Routing.kt` and `service/ArticleService.kt`, adds `plugins/Database.kt`, and adds `ArticleServiceTest.kt` and `RoutingTest.kt` under a new `src/test/kotlin` tree. The description explains why one `java.sql.Connection` shared across coroutines was unsafe, names the pool settings and where each is read from, and pastes the Gradle test summary and the `HikariPool-1 - Start completed` line from the server log.

The run's full record at `GET /o/{org}/sessions/{id}/messages` keeps the `docker compose up` output, the Gradle build and test output with each test class named, and the `curl` loop against the running server. `GET /o/{org}/p/{project}/sessions/{id}/changes` lists every file with its diff. The repository's `build-all.yml` workflow runs `build-all.sh` over every sample on a pull request, so the new tests run there as well.

Before merging, a reviewer checks that every `prepareStatement` now sits inside a `use` block so no connection leaks on an exception, that the pool is closed on shutdown, that `maximumPoolSize` is small enough for the database's `max_connections`, and that the README's run steps still work from a clean checkout. No deployment happens; the pull request is the whole result.

## Run it on every service that opens its own JDBC connection

A team with several Ktor services starts one run per repository from the terminal with `POST /o/{org}/sessions`, this prompt and the repository in `resources`. Each run reads its own build file and data layer, so a service on Exposed gets `Database.connect(dataSource)` instead of a hand-rolled service, and a service that already has a pool gets only the shutdown hook and the tests it lacks. Each run opens its own pull request.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn ends, with `session_url` to read the pull request and the pasted test summary from. A `request_id` per repository returns the run already started when the batch is run again.

## Why run it on Rush?

A shared connection works on a laptop with one browser tab, which is why the bug survives. It fails under overlapping requests, and showing that takes a database, a server and a load loop running together. The agent has all three in its own sandbox: Docker for Postgres, Gradle for the tests and `curl` for the concurrent calls, and it pushes only after the concurrent test passes.

The pull request keeps the evidence with the change: the diff, the test names, the pasted summary and the trajectory with every command. A reviewer sees not just that a pool was added but that the failure it prevents was reproduced and then went away.

## Frequently asked questions

### Why HikariCP rather than the driver's own pooling?

The repository already uses HikariCP 7.0.2 in its `h2` sample, so the dependency, the config class and the startup log are familiar to its maintainers. Hikari is also what the Ktor documentation and the Exposed integration use. The agent reuses the pattern rather than introducing a second pool library.

### Where do the credentials come from now?

From the `db` block in `application.yaml`, which defaults to the user, password and database in `postgres.yaml` so `docker compose up` and `./gradlew run` keep working, and which reads environment variables through Ktor's `$DB_PASSWORD` config syntax for a deployed instance. The reading of `postgres.yaml` with `YamlConfig` at runtime is removed.

### Do the tests need Docker?

Yes. Both test classes connect to the Postgres that `docker-compose.yaml` starts, because the behaviour under test is real concurrent database access. The agent runs them that way in its sandbox. If you prefer self-contained tests, ask for Testcontainers in the prompt and the agent adds the `postgresql` module and starts the container from the test.

### What happens on shutdown?

`configureDatabase()` subscribes to `ApplicationStopping` and calls `close()` on the `HikariDataSource`, so borrowed connections are returned and the pool releases its sockets before the engine stops. The previous code never closed its connection.

## More Ktor jobs

- [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/)
- [Add CSRF Protection to Ktor Form Posts](https://getrush.ai/run/add-csrf-protection/ktor/)

## The same job on other stacks

- [Add Connection Pooling Limits to a Prisma App on Serverless](https://getrush.ai/run/add-connection-pooling/prisma/)
- [Add Connection Pool Settings to a Flask and SQLAlchemy App](https://getrush.ai/run/add-connection-pooling/sqlalchemy/)
- [Add Connection Pooling to a GORM App](https://getrush.ai/run/add-connection-pooling/gorm/)

## 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/)
