Skip to main content

Spring AI Chat Engine

A Spring Boot chat backend on Spring AI. Stores conversations in PostgreSQL, streams model replies, and ships with Docker, rate limiting and OpenAPI docs.

Stack: Java / Spring Boot / Spring AI / PostgreSQL / Flyway / Groq / Docker / Bucket4j / OpenAPI

Open sourceLicence: see repository (opens in a new tab)

What it does

Groq is the hosted service that runs the language model. The app sends the conversation to Groq and returns the reply, either as one JSON response or as a stream.

Conversations

  • Conversations and messages. Create, list, read, rename and delete conversations. The full message history is stored in PostgreSQL, with the schema managed by Flyway.
  • Per-conversation overrides. Each conversation can carry its own system prompt, model and temperature. Otherwise the server defaults apply.

Model calls

  • Replies from Groq. A single JSON response, or a server-sent event stream that delivers the reply while it is generated.
  • Prompt control. The system prompt is always sent first, and only the most recent messages (a sliding window, 20 by default) are sent as history.
  • No transaction held during the model call. The user message and history are read in one short transaction, the model is called with no transaction open, and the reply is saved in a second short one.

Reliability and safety

  • Resilient provider calls. Configurable connect and read timeouts, and retries with exponential backoff for transient failures only (408, 409, 429, 5xx, timeouts, connection errors), honouring the Retry-After header.
  • Predictable errors. Every error has the same five-field JSON body. Provider failures map to 429, 503 or 502 with generic messages that never contain keys or raw provider output.
  • Protection. Per-IP rate limiting on the two message endpoints (Bucket4j), and optional API key authentication through an X-API-Key header. Neither needs Spring Security.

Operations

  • Observability. An X-Request-Id header (accepted or generated) that is echoed in the response and added to every log line, plus a health endpoint via Actuator.
  • Interactive docs. OpenAPI 3.1 and Swagger UI via springdoc-openapi.
  • Ready to ship. A layered, non-root Docker image with a health check, a Docker Compose stack and a GitHub Actions pipeline.

How a request flows

  1. ClientPOST to the message endpoint
  2. FiltersRequest id, optional API key, rate limit
  3. Short transactionTransaction 1Save the user message, read recent history
  4. No transaction openModel callGroq, timeouts and retries. No transaction open
  5. Short transactionTransaction 2Save the reply
  6. ResponseJSON, or an event stream
One message request, from the client to the response. The two filled steps are short database transactions. The dashed step calls the model with no transaction open. Text version: Client: POST to the message endpoint. Then Filters: Request id, optional API key, rate limit. Then Transaction 1: Save the user message, read recent history (short transaction). Then Model call: Groq, timeouts and retries. No transaction open (no transaction open). Then Transaction 2: Save the reply (short transaction). Then Response: JSON, or an event stream.

Run it

Get the code

git clone https://github.com/agentworkshq/spring-ai-chat-engine.git
cd spring-ai-chat-engine

With Docker Compose

Needs Docker with Compose v2 and a Groq API key from the Groq console. Edit .env and set GROQ_API_KEY before the last command. The first build downloads Maven and all dependencies, so it takes a few minutes.

cp .env.example .env # Windows PowerShell: Copy-Item .env.example .env
docker compose up --build

When the app service reports healthy in docker compose ps, the API is ready on port 8080.

Check that it is up

curl http://localhost:8080/actuator/health

Swagger UI is at http://localhost:8080/swagger-ui.html and the raw OpenAPI document is at /v3/api-docs. To stop the stack, run docker compose down.

Without Docker for the app

Runs only the database in Docker and the application with the Maven wrapper.

docker compose up -d postgres
export GROQ_API_KEY=... # PowerShell: $env:GROQ_API_KEY = "..."
./mvnw spring-boot:run # Windows: mvnw.cmd spring-boot:run

Versions, from the build files: Java 21, Spring Boot 4.1.2, Spring AI 2.0.1, PostgreSQL 16 (Docker Compose image).

Environment variables

Names only. Set them in .env or in your shell.

NameWhat it does
GROQ_API_KEYGroq API key. Required, with no default.
GROQ_MODELDefault model, used when a conversation has no model of its own.
DB_NAMEPostgreSQL database name.
DB_USERPostgreSQL user.
DB_PASSWORDPostgreSQL password. Change it outside local development.
SPRING_DATASOURCE_URLFull JDBC URL. Docker Compose points it at the postgres service.
SPRING_DATASOURCE_USERNAMEOverrides the database user directly.
SPRING_DATASOURCE_PASSWORDOverrides the database password directly.
API_KEY_ENABLEDWhen true, requests must send X-API-Key, except health and the OpenAPI docs.
API_KEYThe expected key. Required when API_KEY_ENABLED is true.
RATE_LIMIT_ENABLEDTurns the rate limit on or off.
RATE_LIMIT_RPMRequests per minute per client IP on the two message endpoints. Also the burst size.
LLM_CONNECT_TIMEOUTTimeout for connecting to Groq.
LLM_READ_TIMEOUTLongest wait for Groq, including between streamed chunks.
LLM_MAX_ATTEMPTSTotal attempts per Groq call, the first included. 1 disables retries.
CHAT_HISTORYWINDOWHow many of the most recent messages are sent as history.
CHAT_MAXINPUTCHARSLongest accepted user message, in characters.
CHAT_SYSTEMPROMPTDefault system prompt, used when a conversation has none.
JAVA_OPTSJVM flags in the Docker image. Setting it replaces the image defaults.

API at a glance

MethodPathPurpose
POST/api/v1/conversationsCreate a conversation
GET/api/v1/conversationsList conversations, newest first
GET/api/v1/conversations/{id}Get a conversation with all its messages
PATCH/api/v1/conversations/{id}Update title, system prompt, model or temperature
DELETE/api/v1/conversations/{id}Delete a conversation and its messages
POST/api/v1/conversations/{id}/messagesSend a message, get the reply as JSON
POST/api/v1/conversations/{id}/messages/streamSend a message, stream the reply as server-sent events
GET/actuator/healthHealth check
GET/swagger-ui.htmlSwagger UI
GET/v3/api-docsThe OpenAPI document

Why it exists

It is a reference backend that shows how to put an LLM behind a normal Spring Boot API, with storage, error handling and limits. It follows the ideas in the Java Developer to AI Engineer series. The README lists its limits, for example that rate limit state is kept in memory.