Spring › Wanted-Challenge

Uploading to ImgBB outside Spring database transactions

Use Spring HTTP interfaces for ImgBB and bound the database transaction with TransactionTemplate so remote uploads do not hold connections idle.

Uploading to ImgBB outside Spring database transactions

A slow image upload can hold a database connection idle if both operations sit inside one transaction. I used a Spring HTTP interface for ImgBB and opened the write transaction only after the upload returned.

The examples use Spring Boot 3.5, Spring Framework 6, Kotlin 1.9, and Java 21.

Keeping storage behind a profile-specific interface

Article creation and updates accept multipart attachments. Storing them on a local disk makes scaling out harder because replicas do not automatically share files. Calling ImgBB directly from the article service would also make tests and a future provider change depend on that client.

1
2
3
4
5
6
7
8
// common/storage/StorageService.kt
package org.project.portfolio.common.storage

import org.springframework.web.multipart.MultipartFile

interface StorageService {
    fun uploadFile(file: MultipartFile): String
}

StorageService defines the upload contract. The production and local profiles bind ImgBB. The test profile uses MockStorage to return a fixed URL without credentials or a network request.

1
2
3
4
5
6
7
8
9
10
11
12
13
// src/test/kotlin/org/project/portfolio/config/MockStorage.kt
package org.project.portfolio.config

import org.project.portfolio.common.storage.StorageService
import org.springframework.stereotype.Component
import org.springframework.web.multipart.MultipartFile

@Component
class MockStorage : StorageService {
    override fun uploadFile(file: MultipartFile): String {
        return "https://mock-storage.com/${file.originalFilename}"
    }
}

If I replace ImgBB with Amazon S3 or Cloudflare R2, the article application still deals with file uploads and URLs. The provider-specific HTTP setup stays on the other side of the interface. For integration tests against the real provider, keep a separate test that exercises authentication, request formatting, and timeout behavior.

Configuring the HTTP interface

Client setupDependencyFit
RestClient with @HttpExchangeSpring MVC web starterSynchronous declarative client in a servlet application
WebClient with @HttpExchangeWebFlux HTTP clientNonblocking client for a reactive call path
OpenFeignSpring Cloud OpenFeignDeclarative client in a project already using Spring Cloud

I chose RestClient with @HttpExchange for this MVC project. HttpServiceProxyFactory.createClient() builds the ImgBBClient proxy. It resolves @RequestParam and @RequestPart from the method arguments, and RestClientAdapter executes the multipart request.

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// common/storage/ImgBB.kt
package org.project.portfolio.common.storage

import com.fasterxml.jackson.databind.JsonNode
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Profile
import org.springframework.http.MediaType
import org.springframework.http.client.SimpleClientHttpRequestFactory
import org.springframework.stereotype.Component
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RequestPart
import org.springframework.web.client.RestClient
import org.springframework.web.client.support.RestClientAdapter
import org.springframework.web.multipart.MultipartFile
import org.springframework.web.service.annotation.HttpExchange
import org.springframework.web.service.annotation.PostExchange
import org.springframework.web.service.invoker.HttpServiceProxyFactory
import java.time.Duration

@Component
@Profile("prod", "local")
class ImgBB(
    @Value("\${storage.imgbb.api-key}")
    private val apiKey: String,
) : StorageService {
    private val requestFactory = SimpleClientHttpRequestFactory().apply {
        setConnectTimeout(Duration.ofSeconds(3))
        setReadTimeout(Duration.ofSeconds(10))
    }

    private val factory = HttpServiceProxyFactory.builder()
        .exchangeAdapter(
            RestClientAdapter.create(
                RestClient.builder()
                    .requestFactory(requestFactory)
                    .build(),
            ),
        )
        .build()

    private val imgbbClient = factory.createClient(ImgBBClient::class.java)

    override fun uploadFile(file: MultipartFile): String {
        return imgbbClient
            .uploadImage(
                key = apiKey,
                name = file.originalFilename,
                image = file,
            )["data"]["url"]
            .asText()
    }

    @HttpExchange(url = "https://api.imgbb.com/1")
    interface ImgBBClient {
        @PostExchange("/upload", contentType = MediaType.MULTIPART_FORM_DATA_VALUE)
        fun uploadImage(
            @RequestParam key: String,
            @RequestParam name: String? = null,
            @RequestParam expiration: Int? = null,
            @RequestPart image: MultipartFile,
        ): JsonNode
    }
}

SimpleClientHttpRequestFactory applies a three-second connect timeout and a ten-second read timeout. A connection timeout caps the wait to establish the connection. A read timeout caps an individual blocking read, so it does not establish a total time budget for uploading a large attachment. The application configuration carries the external key and file-size limits.

1
2
3
4
5
6
7
8
9
10
# src/main/resources/application.yml
spring:
  servlet:
    multipart:
      max-file-size: 15MB
      max-request-size: 15MB

storage:
  imgbb:
    api-key: ${IMGBB_API_KEY:your-api-key}

Putting the database write after the upload

If a transactional service acquires a pooled database connection and then blocks on ImgBB, the connection stays tied up during the HTTP wait. With ten connections and ten requests all holding one, an unrelated lookup has to wait. Sufficient contention can surface as SQLTransientConnectionException even when the database itself is healthy.

I made the upload happen first and opened the transaction with TransactionTemplate for the local update.

flowchart TD
    A["Multipart request"] --> B["Upload before transaction"]
    B --> C["Begin database transaction"]
    C --> D["Save article"]
    D --> E["Commit and release"]

A self-call to an @Transactional method usually bypasses Spring’s AOP proxy. Moving the transaction annotation onto a second method in the same class therefore does not solve this problem. TransactionTemplate gives one method an explicit boundary around persistence without adding a second service bean.

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// article/application/ArticleCommandService.kt
@Service
class ArticleCommandService(
    private val articleRepository: ArticleRepository,
    private val userRepository: UserRepository,
    private val storageService: StorageService,
    private val transactionTemplate: TransactionTemplate,
) {
    fun createArticle(
        email: String,
        articleForm: ArticleForm,
    ): ArticleResponse {
        val uploadedImages = articleForm.images.map { storageService.uploadFile(it) }

        return checkNotNull(
            transactionTemplate.execute {
                val user: User = userRepository.findByEmail(email)
                    ?: throw NotFoundException(User::class.java, mapOf("email" to email))

                val article: Article = articleRepository.save(
                    Article.create(
                        title = articleForm.title,
                        content = articleForm.content,
                        authorId = user.id,
                        images = uploadedImages,
                        tags = articleForm.tags,
                    ),
                )

                ArticleResponse.from(
                    article = article,
                    author = UserSummaryResponse.from(user),
                )
            },
        )
    }

    fun updateArticle(
        articleId: Long,
        articleUpdateForm: ArticleUpdateForm,
    ): ArticleResponse {
        val uploadedImages = articleUpdateForm.images?.map { storageService.uploadFile(it) }

        return checkNotNull(
            transactionTemplate.execute {
                val article: Article = articleRepository.findByIdOrNull(articleId)
                    ?: throw NotFoundException(Article::class.java, mapOf("articleId" to articleId))

                article.update(
                    title = articleUpdateForm.title,
                    content = articleUpdateForm.content,
                    images = uploadedImages,
                    tags = articleUpdateForm.tags,
                )

                ArticleResponse.from(
                    article = article,
                    author = UserSummaryResponse.from(
                        userRepository.findByIdOrNull(article.authorId),
                    ),
                )
            },
        )
    }
}

The controller binds the metadata and file inputs with @ModelAttribute and declares multipart/form-data in its API mapping.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// article/presentation/ArticleController.kt (excerpt)
@PostMapping(consumes = ["multipart/form-data"])
@PreAuthorize("isAuthenticated()")
fun createArticle(
    @AuthenticationPrincipal jwt: Jwt,
    @Valid @ModelAttribute articleForm: ArticleForm,
): ResponseEntity<ArticleResponse> {
    return articleCommandService.createArticle(
        email = jwt.subject,
        articleForm = articleForm,
    ).let {
        ResponseEntity
            .created(URI.create("/api/v1/articles/${it.id}"))
            .body(it)
    }
}

An independent transaction around local writes does not compensate an already completed upload. A validation failure, missing row, or constraint violation after the HTTP call can leave a file without an article reference.

Recovering from partial failure

The storage provider and the database commit separately. Plan how to find and remove files that survive a failed local write.

  • Compensation and cleanup. If the provider supports deletion, try a compensating deletion when the database write fails. When deletion cannot complete immediately, record cleanup work for a scheduled retry.
  • Direct client uploads. Once the application spends substantial time relaying bytes, consider short-lived presigned upload URLs to a provider that supports them. Validate the uploaded object before accepting the final article reference.
  • Bounded multipart work. The sample’s images.map { ... } uploads images sequentially. Limit the number and size of attachments so one request cannot hold a servlet worker indefinitely. Keep spring.jpa.open-in-view: false so serialization does not create another long-lived persistence scope.

Verifying the boundary

Run a slow fake storage implementation while making an unrelated read request. The storage delay should occur before the article write opens its transaction. Check connection pool metrics under concurrent requests and confirm that the uploads do not borrow one connection per in-flight request. Then make the fake storage call succeed and force the repository write to fail. The failure case should make the orphan recoverable through the chosen cleanup path.

RestClient is a synchronous HTTP client that provides a fluent API to perform requests. It serves as an abstraction over HTTP libraries, and handles conversion of HTTP request and response content to and from higher level Java objects.
This post is licensed under CC BY 4.0 by the author.