Building an async Gemini image pipeline with Spring AI
Build an async Spring AI 2.0.1 image generation pipeline with Google GenAI ImageModel, @Async workers, and persistent file storage.
Generating images from text prompts typically takes 5 to 15 seconds per request—far too long to block a servlet thread or risk a mobile client timeout. This post builds an asynchronous image generation pipeline with Spring AI 2.0.1’s
GoogleGenAiImageModel, a202 Acceptedjob API backed by@Asyncworkers, and a date-partitioned file storage abstraction.
Tested with Spring Boot 4.1.1, Spring AI 2.0.1, Kotlin 2.3.21, and
gemini-2.5-flash-image.
Why synchronous image endpoints fail under load
Blocking an HTTP request while waiting on an image generation model creates two immediate production failures:
- Servlet thread pool exhaustion: Holding Tomcat worker threads open for 10+ seconds per call starves unrelated fast endpoints under modest concurrency.
- Client and gateway timeouts: Mobile clients, browsers, and reverse proxies (Nginx, ALB, Cloudflare) commonly enforce 10–30 second read timeouts, turning slow generations into dropped connections and duplicate retries.
Splitting submission from execution solves both problems. The controller persists a PENDING job record and returns 202 Accepted immediately, while an @Async worker calls Gemini, decodes the Base64 image bytes, writes them to storage, and updates the job status to COMPLETED.
flowchart TD
Submit["POST /api/images/jobs"] --> Pending["Save PENDING job & return 202 Accepted"]
Pending --> Worker["@Async ImageJobWorker (PROCESSING)"]
Worker --> Model["GoogleGenAiImageModel (Base64 response)"]
Model --> Storage["Local or S3 ImageStorage"]
Storage --> Done["Mark COMPLETED & serve via /download"]
Sync vs. @Async vs. external message broker
| Approach | Servlet thread impact | Survives app restart | Operational complexity | Best fit |
|---|---|---|---|---|
| Synchronous HTTP call | High (blocks 5–15s) | No | Lowest | Internal tools, single-user prototypes |
Spring @Async + DB job table | Low (returns in <50ms) | Partial (in-flight jobs need recovery) | Low | Moderate traffic, single or few app instances |
| External queue (Kafka / SQS / Redis Streams) | Low | Yes (durable retries & DLQ) | Higher | High throughput, strict retry SLAs, multi-worker scaling |
When not to use @Async alone: If you run auto-scaled pods that terminate frequently or need guaranteed retries after a JVM crash, an in-process @Async executor isn’t enough. Move the worker trigger to SQS, Kafka, or a transactional outbox poller while keeping the same ImageGenerationService and ImageStorage interfaces.
Project setup and configuration
The complete runnable module is in spring-ai-examples (image-generation).
build.gradle.kts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
plugins {
kotlin("jvm") version "2.3.21"
kotlin("plugin.spring") version "2.3.21"
id("org.springframework.boot") version "4.1.1"
id("io.spring.dependency-management") version "1.1.7"
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.ai:spring-ai-starter-model-google-genai")
runtimeOnly("com.h2database:h2")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
}
application.yaml
Configure gemini-2.5-flash-image, a default 1:1 aspect ratio, an H2 database for job tracking, and a local base directory for generated images:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
server:
port: 8085
spring:
application:
name: image-generation
ai:
google:
genai:
api-key: ${SPRING_AI_GOOGLE_GENAI_API_KEY}
image:
model: gemini-2.5-flash-image
aspect-ratio: "1:1"
datasource:
url: jdbc:h2:mem:image-generation
jpa:
hibernate:
ddl-auto: create-drop
image:
storage:
local:
base-dir: ./generated-images
Do not set the
person-generationoption when authenticating with a standard Google AI Studio API key. That option is supported only in Google Cloud Vertex AI mode and throws anIllegalArgumentExceptionotherwise.
Calling ImageModel and decoding Base64 output
Google GenAI’s image model returns generated binaries as Base64-encoded strings (b64Json). ImageGenerationService builds GoogleGenAiImageOptions, invokes ImageModel, extracts the MIME type from GoogleGenAiImageGenerationMetadata, and decodes the bytes:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package io.github.cmsong111.image_generation.service
import io.github.cmsong111.image_generation.dto.GeneratedImage
import io.github.cmsong111.image_generation.dto.ImageGenerationRequest
import org.springframework.ai.google.genai.image.GoogleGenAiImageGenerationMetadata
import org.springframework.ai.google.genai.image.GoogleGenAiImageOptions
import org.springframework.ai.image.ImageModel
import org.springframework.ai.image.ImagePrompt
import org.springframework.stereotype.Service
import java.util.Base64
@Service
class ImageGenerationService(
private val imageModel: ImageModel,
) {
fun generate(request: ImageGenerationRequest): GeneratedImage {
val options = GoogleGenAiImageOptions.builder()
.aspectRatio(request.aspectRatio)
.imageSize(request.imageSize)
.build()
val response = imageModel.call(ImagePrompt(request.prompt, options))
val modelText = response.metadata.get<String>("text")
val generation = response.results.firstOrNull { it.output.b64Json != null }
?: throw ImageGenerationException("No image was generated: ${modelText ?: "empty response"}")
val mimeType = (generation.metadata as? GoogleGenAiImageGenerationMetadata)?.mimeType
?: "image/png"
return GeneratedImage(
bytes = Base64.getDecoder().decode(generation.output.b64Json),
mimeType = mimeType,
modelText = modelText,
)
}
}
Checking response.metadata.get<String>("text") is useful for debugging: when the model declines a prompt or returns text instead of an image, that field explains why no b64Json payload came back.
Persistent storage and the @Async worker
Keeping storage behind an ImageStorage interface lets you develop against the local filesystem and swap in an S3 implementation for production without touching the worker.
Date-partitioned local storage
Partitioning files under YYYY-MM-DD/<uuid>.<ext> prevents a single directory from accumulating millions of files and simplifies retention cleanup:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package io.github.cmsong111.image_generation.storage
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Component
import java.nio.file.Files
import java.nio.file.Path
import java.time.LocalDate
@Component
class LocalFileSystemImageStorage(
@Value("\${image.storage.local.base-dir}") baseDir: String
) : ImageStorage {
private val root: Path = Path.of(baseDir).toAbsolutePath().normalize()
override fun store(bytes: ByteArray, extension: String): String {
val today = LocalDate.now().toString()
val dir = root.resolve(today)
Files.createDirectories(dir)
val filename = "${java.util.UUID.randomUUID()}.$extension"
val target = dir.resolve(filename)
Files.write(target, bytes)
return "$today/$filename"
}
override fun load(storedPath: String): ByteArray {
return Files.readAllBytes(root.resolve(storedPath))
}
}
Background job worker (@Async)
The worker runs on a dedicated imageJobExecutor thread pool so image generation never competes with Spring’s default task executor:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@Component
class ImageJobWorker(
private val imageGenerationService: ImageGenerationService,
private val imageStorage: ImageStorage,
private val jobRepository: ImageJobRepository,
) {
private val log = LoggerFactory.getLogger(javaClass)
@Async("imageJobExecutor")
fun process(jobId: String) {
val job = jobRepository.findById(jobId).orElse(null) ?: return
job.markProcessing()
jobRepository.save(job)
try {
val generated = imageGenerationService.generate(
ImageGenerationRequest(prompt = job.prompt, aspectRatio = job.aspectRatio)
)
val extension = if (generated.mimeType.contains("jpeg")) "jpg" else "png"
val storedPath = imageStorage.store(generated.bytes, extension)
job.markCompleted(storedPath, generated.mimeType, generated.modelText)
jobRepository.save(job)
log.info("Image job {} completed: {}", jobId, storedPath)
} catch (ex: Exception) {
log.error("Image job {} failed", jobId, ex)
job.markFailed(ex.message ?: "Unknown error")
jobRepository.save(job)
}
}
}
Testing and end-to-end verification
ImageJobFlowTests verifies the full state machine (PENDING → PROCESSING → COMPLETED) and storage persistence using @MockitoBean for ImageModel:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@SpringBootTest(properties = ["image.storage.local.base-dir=build/test-generated-images"])
class ImageJobFlowTests {
@MockitoBean
private lateinit var imageModel: ImageModel
@Autowired
private lateinit var imageJobService: ImageJobService
@Test
fun `submits job and stores generated image asynchronously`() {
val submitted = imageJobService.submit(ImageGenerationRequest(prompt = "Blog thumbnail"))
assertThat(submitted.status).isEqualTo(ImageJobStatus.PENDING)
val completed = awaitTerminalState(submitted.id)
assertThat(completed.status).isEqualTo(ImageJobStatus.COMPLETED)
assertThat(completed.mimeType).isEqualTo("image/png")
}
}
Test execution output
Figure 1. JUnit 5 test confirming async job execution and persistent file storage.
Polling the REST API with curl
Submitting a job returns 202 Accepted with a job ID. Polling GET /api/images/jobs/{id} returns the downloadUrl once the worker marks the job COMPLETED:
Figure 2. REST polling flow from 202 Accepted (PENDING) through COMPLETED.
Browser preview of the stored image
Opening /api/images/jobs/{id}/download streams the stored image/png binary back to the browser:
Figure 3. Generated 16:9 image served directly from local storage via the download endpoint.
Production caveats and checklist
Before deploying this pattern to production, harden four areas:
- Guard against path traversal in
load(storedPath): Always resolvestoredPathagainstroot, normalize it, and verifyresolved.startsWith(root)before reading bytes from disk. - Trigger
@Asyncafter transaction commit: IfImageJobService.submit()saves thePENDINGrow inside@Transactionaland immediately callsworker.process(jobId), the background thread may query the database before the commit is visible. Dispatch the worker from aTransactionSynchronization.afterCommitcallback orTransactionalEventListener(phase = AFTER_COMMIT). - Bound the
imageJobExecutorpool and queue: Set explicitcorePoolSize,maxPoolSize, andqueueCapacitywith a rejection policy (AbortPolicyreturning429 Too Many Requests) so traffic spikes don’t OOM the JVM with queued Base64 buffers. - Swap local disk for object storage in multi-pod deployments: Local files aren’t shared across pods. Replace
LocalFileSystemImageStoragewith S3 or GCS and return short-lived presigned URLs instead of streaming binaries through Spring MVC.
Pre-deploy checklist
- Use a dedicated, bounded
ThreadPoolTaskExecutorforimageJobExecutor. - Dispatch async workers only after the
PENDINGjob transaction commits. - Omit
person-generationunless running on Vertex AI. - Validate resolved storage paths against the root directory (or move to S3/GCS with presigned URLs).
The complete source code for this walkthrough is in cmsong111/spring-ai-examples/image-generation.