Home / Blog / Wrap an Amazon Product API in a Kotlin Ktor Microservice: Caching and Validation

Wrap an Amazon Product API in a Kotlin Ktor Microservice: Caching and Validation

Wrap the SellerMagnet API in a small Ktor microservice: a regex and a set membership check validate the ASIN and marketplace before any network call, a ConcurrentHashMap-backed TTL cache answers repeat lookups for free, and the Kotlin quickstart's own Client.kt and Models.kt are reused unchanged. Every scenario, including a concurrent cache read from Netty's coroutine pool, runs against a fails-closed fake HTTP server through Ktor's own embedded test engine, not described by hand.

December 02, 2026
7 min read
SellerMagnet Team
Share & Bookmark
Code editor validating a lookup request before any network call in a Ktor route handler

A Kotlin Ktor microservice in front of the SellerMagnet API validates every request with a regex and a set membership check before it can spend a credit, answers repeat lookups from a ConcurrentHashMap-backed in-process cache, and retries only the status codes a second attempt can fix. This guide builds that wrapper - Validate.kt, Cache.kt and Server.kt are new, and the Kotlin quickstart's own Client.kt and Models.kt are reused unchanged - and tests all of it through Ktor's own testApplication embedded test engine against a fails-closed fake HTTP server, so nothing here is just described.

Key Takeaways

  • Validate asin and marketplace_id before the upstream call, so a bad request costs nothing and waits on no timeout.
  • TtlCache needs a ConcurrentHashMap here, unlike a single-worker-process plain dict: Ktor's Netty engine runs route handlers from a shared coroutine pool, so two requests for the same ASIN can run concurrently on the same JVM.
  • The retry policy is the quickstart's own: 429 waits for free, a 500 is retried once (it is refunded), 502/503 are retried up to 4 times (each billed), and a 404 is a real answer, never retried.
  • A plain connection failure is not an ApiError, so it never reaches withRetry's billed-status branch at all; Client.get() lets java.net.ConnectException propagate straight out, uncaught and unretried.
  • Client.kt and Models.kt do not change between a coroutine-per-request Ktor route and the quickstart's own single-threaded script: the same java.net.http.HttpClient fits both.

Why wrap the API in a microservice instead of calling it directly?

A thin service in front of the API gives every caller in a larger system one place that enforces the request shape, one cache for ASINs several callers ask for repeatedly, and one retry policy, instead of each caller reimplementing the Kotlin quickstart's Client.kt and Models.kt on its own. This post reuses those two files unchanged - the single HttpClient the quickstart's Client class builds is already documented safe for concurrent use, which is exactly how Ktor calls a route handler for every request.

Dependencies (Maven; Gradle works the same way)

mkdir -p src/main/kotlin/sellermagnet && cd amazon-ktor
# pom.xml: kotlin-maven-plugin + io.ktor:ktor-server-core-jvm, ktor-server-netty-jvm,
# ktor-server-test-host-jvm (test scope), com.google.code.gson:gson
export SELLERMAGNET_API_KEY="your-key-here"
mvn compile exec:java -Dexec.mainClass=sellermagnet.ServerKt

How do I validate the ASIN and marketplace before spending a credit?

Put the shape checks in one function and call it before any network call. An ASIN is always 10 upper-case letters or digits - reusing Client.isAsin, the quickstart's own \A...\z-anchored check, not ^...$ (a trailing newline from a copy-pasted ASIN slips past ^...$ in Kotlin/Java regex, a documented trap in the quickstart post itself). The marketplace ID must be one this wrapper actually supports (the full list of all 23 marketplace IDs is in the marketplace IDs list). A failing check throws a ValidationException before the route handler ever opens a connection, so a malformed request never waits on the 120-second timeout and never costs a credit.

Validate.kt - checked before any network call

package sellermagnet

// The marketplace IDs this wrapper covers; the full list of all 23 is in
// https://sellermagnet-api.com/blog/amazon-marketplace-ids-list
val MARKETPLACE_IDS: Set<String> = setOf(
    "ATVPDKIKX0DER",  // amazon.com
    "A1PA6795UKMFR9", // amazon.de
    "A1F83G8C2ARO7P", // amazon.co.uk
    "A13V1IB3VIYZZH", // amazon.fr
)

/** One field that failed validation, with a message safe to show a caller. */
data class FieldError(val field: String, val msg: String)

class ValidationException(val errors: List<FieldError>) : RuntimeException("invalid lookup request")

/**
 * Checks the ASIN shape and marketplace membership before any network call, so a bad request
 * never opens a connection, never waits on the client's 120 s timeout, and never spends a
 * credit. Uses Client.isAsin (the quickstart's own `\A...\z` anchored check, not `^...$` - a
 * trailing newline from a copy-pasted ASIN slips past `^...$` in Kotlin/Java regex).
 */
fun validateLookupRequest(asinRaw: String, marketplaceId: String): Pair<String, String> {
    val asin = asinRaw.trim().uppercase()
    val errors = mutableListOf<FieldError>()
    if (!Client.isAsin(asin)) {
        errors.add(FieldError("asin", "asin must be 10 upper-case letters/digits"))
    }
    if (!MARKETPLACE_IDS.contains(marketplaceId)) {
        errors.add(FieldError("marketplace_id", "unknown marketplace_id: $marketplaceId"))
    }
    if (errors.isNotEmpty()) throw ValidationException(errors)
    return asin to marketplaceId
}

How does the cache stay safe when Ktor calls route handlers concurrently?

TtlCache is a plain map keyed by asin:marketplaceId, with each entry carrying its own expiry, but backed by ConcurrentHashMap instead of a plain HashMap. A web framework whose request handlers run one at a time per worker only ever touches its process's dict from one caller at a time; Ktor's Netty engine dispatches a route's suspend handler from a shared coroutine pool, so two lookups for the same ASIN arriving together can run concurrently on the same JVM - a plain HashMap can corrupt its own internal structure under a concurrent put/get, not just race on stale data. A lookup within the TTL (300 seconds here) returns the stored result with cached: true and makes no network call at all; this service also runs as one process, so running several replicas behind a load balancer still means each one keeps its own cache, the same single-process trade-off any in-process cache carries, not hidden here either.

Cache.kt - a ConcurrentHashMap-backed in-process TTL cache

package sellermagnet

import java.time.Instant
import java.util.concurrent.ConcurrentHashMap

/** One cached lookup result plus when it expires. */
private data class CacheEntry(val value: LookupResult, val expiresAt: Instant)

/**
 * A TTL cache keyed by "asin:marketplaceId". Backed by ConcurrentHashMap instead of a plain
 * HashMap: Ktor's Netty engine calls a route's suspend handler from a shared coroutine pool, so
 * two coroutines can run the same route concurrently on the same JVM - unlike a single-worker,
 * one-request-at-a-time process, a plain HashMap here can corrupt its internal structure under a
 * concurrent put/get, not just race on stale data.
 */
class TtlCache(private val ttlSeconds: Long) {
    private val store = ConcurrentHashMap<String, CacheEntry>()

    fun get(key: String): LookupResult? {
        val entry = store[key] ?: return null
        if (Instant.now().isAfter(entry.expiresAt)) {
            store.remove(key) // expired: evict so size() reflects only live entries
            return null
        }
        return entry.value
    }

    fun put(key: String, value: LookupResult) {
        store[key] = CacheEntry(value, Instant.now().plusSeconds(ttlSeconds))
    }

    fun size(): Int = store.size
}

What does the Ktor route itself look like?

The handler validates the path and query parameters first, checks the cache, and only then calls the quickstart's own Client.lookup(), which runs through the quickstart's own HttpClient. A plain connection failure - java.net.ConnectException from a refused connection, not an ApiError - is never caught by Client.get() at all, so it propagates straight out of the route and is handled as its own branch, separate from the billed ApiError case.

Server.kt - the Ktor microservice

package sellermagnet

import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import com.google.gson.GsonBuilder
import com.google.gson.JsonObject

/** The trimmed shape returned to the caller; price stays null for "N/A" (no featured offer). */
data class LookupResult(val asin: String, val price: Double?, val currency: String, val cached: Boolean)

// Gson omits null fields by default; serializeNulls() keeps "price": null in the response
// instead of dropping the key, so a caller can tell "no featured offer" from "field missing".
private val gson = GsonBuilder().serializeNulls().create()

/**
 * Wires one route: GET /lookup/{asin}?marketplace_id=.... Validate.kt and Cache.kt are new;
 * Client.kt and Models.kt are the Kotlin quickstart's own files, unchanged - Client is built
 * once per application (like the quickstart's single HttpClient) and reused across requests,
 * since java.net.http.HttpClient is documented safe for concurrent use.
 */
fun Application.wrapperModule(client: Client, cache: TtlCache) {
    routing {
        get("/lookup/{asin}") {
            val asinParam = call.parameters["asin"] ?: ""
            val marketplaceId = call.request.queryParameters["marketplace_id"] ?: ""

            val (asin, mkt) = try {
                validateLookupRequest(asinParam, marketplaceId)
            } catch (e: ValidationException) {
                val detail = JsonObject()
                detail.add("errors", gson.toJsonTree(e.errors))
                call.respondText(gson.toJson(detail), ContentType.Application.Json, HttpStatusCode.BadRequest)
                return@get
            }

            val cacheKey = "$asin:$mkt"
            val hit = cache.get(cacheKey)
            if (hit != null) {
                call.respondText(gson.toJson(hit.copy(cached = true)), ContentType.Application.Json, HttpStatusCode.OK)
                return@get
            }

            try {
                val product = client.lookup(asin, mkt)
                val result = LookupResult(asin = product.asin, price = product.buyBoxPrice,
                    currency = product.currencyCode, cached = false)
                cache.put(cacheKey, result)
                call.respondText(gson.toJson(result), ContentType.Application.Json, HttpStatusCode.OK)
            } catch (e: ApiError) {
                if (e.status == 404) {
                    val detail = JsonObject(); detail.addProperty("detail", "asin not found on this marketplace")
                    call.respondText(gson.toJson(detail), ContentType.Application.Json, HttpStatusCode.NotFound)
                } else {
                    // Every other ApiError (429 exhausted, 500/502/503 past the retry cap, a
                    // client timeout) surfaces as one 502: the caller cannot tell from this
                    // response alone whether the upstream request was billed - see the
                    // quickstart post for the per-status billing table.
                    val detail = JsonObject(); detail.addProperty("detail", "upstream lookup failed: ${e.message}")
                    call.respondText(gson.toJson(detail), ContentType.Application.Json, HttpStatusCode.BadGateway)
                }
            } catch (e: java.net.ConnectException) {
                // Not an ApiError at all: Client.get() never catches a raw connection exception,
                // verified in the mock-testing-kotlin post. Nothing was billed for this attempt.
                val detail = JsonObject(); detail.addProperty("detail", "upstream connection refused")
                call.respondText(gson.toJson(detail), ContentType.Application.Json, HttpStatusCode.BadGateway)
            }
        }
    }
}

fun main() {
    val client = Client.fromEnv()
    val cache = TtlCache(ttlSeconds = 300)
    embeddedServer(Netty, port = 8080) { wrapperModule(client, cache) }.start(wait = true)
}

A client timeout is not the same as a free connection error

The ApiError branch above covers every billed failure including a client timeout, which Client.kt's get() reports with status 0 after the request already reached the server - the credit is deducted before the scrape even starts, so a client that gives up waiting has still paid for an answer it will never see, and that credit is not refunded (refunds only exist for a server-side 500 without Retry-After). Keep the client timeout at 120 seconds, matching the quickstart's own HttpClient, rather than cutting it short to "fail fast".

Flow diagram of a lookup request through validation, cache and the upstream API
A cache hit never reaches the upstream API; a cache miss stores the result before answering.

Trimmed response for a cache-miss lookup

{
  "asin": "B0CL61F39H",
  "price": 444.99,
  "currency": "USD",
  "cached": false
}
Every scenario the test suite covers, and what each one costs in credits.
ScenarioHTTP statusRetried?Billed?
Valid ASIN, cache miss200-Yes (1 credit)
Same lookup again within 300s200 (cached)noNo - 0 upstream calls
Malformed ASIN shape400noNo - rejected before the network
Unknown marketplace_id400noNo - rejected before the network
Lower-case ASIN, cache miss200-Yes - normalized then looked up
Upstream 404 (not on this marketplace)404noYes - a real answer
Upstream 429 (concurrency cap)200 (after a wait)yes - freeNo - the 429 itself
Upstream 500 (refunded)200 (after 1 retry)yes, capped at 1No - the 500 itself
Two upstream 500s in a row502no - stopsNo - the 500s
Upstream 502 / 503502yes, up to 4 attemptsYes - every attempt
Connection refused (never reached the server)502no - not an ApiErrorNo - nothing was billed
Table of every tested scenario, its HTTP status, retry behaviour and credit cost
Every row is a real Ktor testApplication assertion against a fails-closed fake HTTP server, not a described behaviour.

How do the tests fake the upstream API without Ktor's own MockEngine?

FakeServer.kt is the com.sun.net.httpserver.HttpServer-based fake the Kotlin mock-testing guide already built for Client.kt's own base constructor seam: a real local HTTP server, scripted per test, that fails closed with a 500 "no route installed" when a test forgets to enqueue a response. The route layer itself is tested through Ktor's own testApplication - the embedded test engine Ktor ships for exactly this - which starts the real wrapperModule application in-process and gives each test its own HTTP client to call it with, so both the routing code and the upstream client get exercised for real, not mocked at either layer.

FakeServer.kt - the mock-testing post's own fake, reused unchanged

package sellermagnet.tests

import com.sun.net.httpserver.HttpExchange
import com.sun.net.httpserver.HttpServer
import java.net.InetSocketAddress
import java.nio.charset.StandardCharsets

/**
 * A real local HTTP server (com.sun.net.httpserver.HttpServer, JDK standard library, no Netty/
 * Ktor dependency), scripted per test. Drives the unmodified sellermagnet.Client/Models through
 * the client's own SELLERMAGNET_API_BASE seam (its constructor's "base" parameter already reads
 * that environment variable, documented for pointing at a local mock in tests), never a
 * hand-written fake of Client itself.
 */
data class FakeResponse(val status: Int, val body: String, val retryAfter: String? = null)

class FakeServer {
    private val server: HttpServer = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)
    private val script = mutableListOf<FakeResponse>()
    private var index = 0
    private val requests = mutableListOf<String>()
    val requestCount: Int get() = synchronized(requests) { requests.size }

    init {
        server.createContext("/") { exchange -> handle(exchange) }
        server.executor = null
        server.start()
    }

    val base: String get() = "http://127.0.0.1:${server.address.port}"

    /** Scripts the next response. A request with no scripted response left fails closed: 500
     *  "no route installed", never a plausible empty 200. */
    fun enqueue(status: Int, body: String, retryAfter: String? = null): FakeServer {
        synchronized(script) { script.add(FakeResponse(status, body, retryAfter)) }
        return this
    }

    private fun handle(exchange: HttpExchange) {
        synchronized(requests) { requests.add(exchange.requestURI.toString()) }
        val entry = synchronized(script) {
            if (index < script.size) script[index++]
            else FakeResponse(500, "{\"success\":false,\"message\":\"no route installed\"}")
        }
        val bytes = entry.body.toByteArray(StandardCharsets.UTF_8)
        if (entry.retryAfter != null) {
            exchange.responseHeaders.add("Retry-After", entry.retryAfter)
        }
        exchange.responseHeaders.add("Content-Type", "application/json")
        exchange.sendResponseHeaders(entry.status, bytes.size.toLong())
        exchange.responseBody.use { it.write(bytes) }
    }

    fun stop() = server.stop(0)
}

ServerTest.kt - 14 scenarios against Ktor's embedded test engine, run for real below

package sellermagnet.tests

import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.testing.*
import sellermagnet.Client
import sellermagnet.TtlCache
import sellermagnet.wrapperModule
import com.google.gson.JsonParser
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlin.test.assertFalse

/**
 * 14 scenarios against a real Ktor application started by testApplication (the embedded test
 * engine Ktor ships for exactly this), with a real local FakeServer.kt (com.sun.net.httpserver,
 * from the mock-testing-kotlin post) standing in for the live SellerMagnet API through Client's
 * own SELLERMAGNET_API_BASE-style "base" constructor seam. Client.kt and Models.kt run
 * completely unmodified; only Validate.kt, Cache.kt and Server.kt (this post) are new.
 */
class ServerTest {

    private fun testClient(server: FakeServer, waits: MutableList<Double>? = null) =
        Client(key = "test-key", base = server.base, sleeper = { s -> waits?.add(s) ?: Unit })

    @Test
    fun validLookupReturnsPriceAndIsNotCached() = testApplication {
        val server = FakeServer()
        try {
            application { wrapperModule(testClient(server), TtlCache(300)) }
            server.enqueue(200, """{"success":true,"data":{"productInfo":{"asin":"B0CL61F39H","buyBoxInfo":{"price":444.99,"currencyCode":"USD"}}}}""")
            val resp = client.get("/lookup/B0CL61F39H?marketplace_id=ATVPDKIKX0DER")
            assertEquals(HttpStatusCode.OK, resp.status)
            val body = JsonParser.parseString(resp.bodyAsText()).asJsonObject
            assertFalse(body.get("cached").asBoolean)
            assertEquals(444.99, body.get("price").asDouble)
            assertEquals(1, server.requestCount)
        } finally { server.stop() }
    }

    @Test
    fun secondLookupIsServedFromCacheWithoutASecondUpstreamCall() = testApplication {
        val server = FakeServer()
        try {
            val cache = TtlCache(300)
            application { wrapperModule(testClient(server), cache) }
            server.enqueue(200, """{"success":true,"data":{"productInfo":{"asin":"B0CL61F39H","buyBoxInfo":{"price":444.99,"currencyCode":"USD"}}}}""")
            client.get("/lookup/B0CL61F39H?marketplace_id=ATVPDKIKX0DER")
            val resp2 = client.get("/lookup/B0CL61F39H?marketplace_id=ATVPDKIKX0DER")
            assertEquals(HttpStatusCode.OK, resp2.status)
            val body = JsonParser.parseString(resp2.bodyAsText()).asJsonObject
            assertTrue(body.get("cached").asBoolean)
            assertEquals(1, server.requestCount) // still just the first call, not a second
        } finally { server.stop() }
    }

    @Test
    fun malformedAsinIsRejectedBefore400AndNoUpstreamCall() = testApplication {
        val server = FakeServer()
        try {
            application { wrapperModule(testClient(server), TtlCache(300)) }
            val resp = client.get("/lookup/short?marketplace_id=ATVPDKIKX0DER")
            assertEquals(HttpStatusCode.BadRequest, resp.status)
            assertEquals(0, server.requestCount) // rejected before any network call
        } finally { server.stop() }
    }

    @Test
    fun unknownMarketplaceIsRejectedBefore400AndNoUpstreamCall() = testApplication {
        val server = FakeServer()
        try {
            application { wrapperModule(testClient(server), TtlCache(300)) }
            val resp = client.get("/lookup/B0CL61F39H?marketplace_id=A_NOT_A_REAL_ONE")
            assertEquals(HttpStatusCode.BadRequest, resp.status)
            assertEquals(0, server.requestCount)
        } finally { server.stop() }
    }

    @Test
    fun lowerCaseAsinIsNormalizedThenLookedUp() = testApplication {
        val server = FakeServer()
        try {
            application { wrapperModule(testClient(server), TtlCache(300)) }
            server.enqueue(200, """{"success":true,"data":{"productInfo":{"asin":"B0CL61F39H","buyBoxInfo":{"price":444.99,"currencyCode":"USD"}}}}""")
            val resp = client.get("/lookup/b0cl61f39h?marketplace_id=ATVPDKIKX0DER")
            assertEquals(HttpStatusCode.OK, resp.status)
            assertEquals(1, server.requestCount)
        } finally { server.stop() }
    }

    @Test
    fun upstream404IsAnswerNotRetried() = testApplication {
        val server = FakeServer()
        try {
            application { wrapperModule(testClient(server), TtlCache(300)) }
            server.enqueue(404, """{"success":false,"message":"Invalid product"}""")
            val resp = client.get("/lookup/B0NOTFOUND?marketplace_id=ATVPDKIKX0DER")
            assertEquals(HttpStatusCode.NotFound, resp.status)
            assertEquals(1, server.requestCount) // one attempt only: a 404 is a real answer
        } finally { server.stop() }
    }

    @Test
    fun upstream429IsFreeAndRetriedUntilItSucceeds() = testApplication {
        val server = FakeServer()
        try {
            val waits = mutableListOf<Double>()
            application { wrapperModule(testClient(server, waits), TtlCache(300)) }
            server.enqueue(429, """{"success":false,"message":"Max concurrent requests"}""", retryAfter = "1")
            server.enqueue(200, """{"success":true,"data":{"productInfo":{"asin":"B0CL61F39H","buyBoxInfo":{"price":444.99,"currencyCode":"USD"}}}}""")
            val resp = client.get("/lookup/B0CL61F39H?marketplace_id=ATVPDKIKX0DER")
            assertEquals(HttpStatusCode.OK, resp.status)
            assertEquals(2, server.requestCount)
            assertTrue(waits.isNotEmpty() && waits[0] >= 1.0) // honoured Retry-After
        } finally { server.stop() }
    }

    @Test
    fun upstream500IsRefundedAndRetriedExactlyOnce() = testApplication {
        val server = FakeServer()
        try {
            val waits = mutableListOf<Double>()
            application { wrapperModule(testClient(server, waits), TtlCache(300)) }
            server.enqueue(500, """{"success":false,"message":"internal error"}""")
            server.enqueue(200, """{"success":true,"data":{"productInfo":{"asin":"B0CL61F39H","buyBoxInfo":{"price":444.99,"currencyCode":"USD"}}}}""")
            val resp = client.get("/lookup/B0CL61F39H?marketplace_id=ATVPDKIKX0DER")
            assertEquals(HttpStatusCode.OK, resp.status)
            assertEquals(2, server.requestCount)
        } finally { server.stop() }
    }

    @Test
    fun twoConsecutive500sStopInsteadOfLoopingForever() = testApplication {
        val server = FakeServer()
        try {
            application { wrapperModule(testClient(server), TtlCache(300)) }
            server.enqueue(500, """{"success":false,"message":"internal error"}""")
            server.enqueue(500, """{"success":false,"message":"internal error"}""")
            val resp = client.get("/lookup/B0CL61F39H?marketplace_id=ATVPDKIKX0DER")
            assertEquals(HttpStatusCode.BadGateway, resp.status)
            assertEquals(2, server.requestCount) // stops at the second 500, never a third attempt
        } finally { server.stop() }
    }

    @Test
    fun upstream502And503AreRetriedUpToTheAttemptCap() = testApplication {
        val server = FakeServer()
        try {
            application { wrapperModule(testClient(server), TtlCache(300)) }
            server.enqueue(502, """{"success":false,"message":"bad gateway"}""")
            server.enqueue(503, """{"success":false,"message":"unavailable"}""")
            server.enqueue(502, """{"success":false,"message":"bad gateway"}""")
            server.enqueue(503, """{"success":false,"message":"unavailable"}""")
            val resp = client.get("/lookup/B0CL61F39H?marketplace_id=ATVPDKIKX0DER")
            assertEquals(HttpStatusCode.BadGateway, resp.status)
            assertEquals(4, server.requestCount) // capped at 4 attempts total, never a 5th
        } finally { server.stop() }
    }

    @Test
    fun connectionRefusedIsNeverBilledAndSurfacesAs502() = testApplication {
        // No FakeServer listening at all: point Client at a port nothing listens on.
        application { wrapperModule(Client(key = "test-key", base = "http://127.0.0.1:1"), TtlCache(300)) }
        val resp = client.get("/lookup/B0CL61F39H?marketplace_id=ATVPDKIKX0DER")
        assertEquals(HttpStatusCode.BadGateway, resp.status)
        val body = JsonParser.parseString(resp.bodyAsText()).asJsonObject
        assertTrue(body.get("detail").asString.contains("connection refused"))
    }

    @Test
    fun naPriceStaysNullNeverZero() = testApplication {
        val server = FakeServer()
        try {
            application { wrapperModule(testClient(server), TtlCache(300)) }
            server.enqueue(200, """{"success":true,"data":{"productInfo":{"asin":"B0CL61F39H","buyBoxInfo":{"price":"N/A","currencyCode":"USD"}}}}""")
            val resp = client.get("/lookup/B0CL61F39H?marketplace_id=ATVPDKIKX0DER")
            assertEquals(HttpStatusCode.OK, resp.status)
            val body = JsonParser.parseString(resp.bodyAsText()).asJsonObject
            assertTrue(body.get("price").isJsonNull)
        } finally { server.stop() }
    }

    @Test
    fun concurrentLookupsOfTheSameAsinShareOneCacheSafely() = testApplication {
        val server = FakeServer()
        try {
            val cache = TtlCache(300)
            application { wrapperModule(testClient(server), cache) }
            server.enqueue(200, """{"success":true,"data":{"productInfo":{"asin":"B0CL61F39H","buyBoxInfo":{"price":444.99,"currencyCode":"USD"}}}}""")
            // Prime the cache once, then fire 20 concurrent cached reads: none of them may
            // touch the fake server again, and TtlCache's ConcurrentHashMap must not corrupt
            // its size() under concurrent get() calls from Netty's shared coroutine pool.
            client.get("/lookup/B0CL61F39H?marketplace_id=ATVPDKIKX0DER")
            val threads = (1..20).map {
                Thread {
                    kotlinx.coroutines.runBlocking {
                        client.get("/lookup/B0CL61F39H?marketplace_id=ATVPDKIKX0DER")
                    }
                }
            }
            threads.forEach { it.start() }
            threads.forEach { it.join() }
            assertEquals(1, server.requestCount)
            assertEquals(1, cache.size())
        } finally { server.stop() }
    }

    @Test
    fun fakeServerFailsClosedWithoutAnEnqueuedResponse() = testApplication {
        val server = FakeServer()
        try {
            application { wrapperModule(testClient(server), TtlCache(300)) }
            // Nothing enqueued: FakeServer answers 500 "no route installed", not a plausible 200.
            // A 500 without Retry-After is refunded and retried once by Client's own policy, so
            // the fake sees it twice before withRetry gives up on the second consecutive 500.
            val resp = client.get("/lookup/B0CL61F39H?marketplace_id=ATVPDKIKX0DER")
            assertEquals(HttpStatusCode.BadGateway, resp.status)
            assertEquals(2, server.requestCount)
        } finally { server.stop() }
    }
}

Real output: mvn test (unmodified run)

[INFO] Running sellermagnet.tests.ServerTest
amazon-product-lookup: 500: internal error (retry 1/3 in 2.0s)
amazon-product-lookup: 500: internal error (retry 1/3 in 2.0s)
amazon-product-lookup: 429: Max concurrent requests (retry 1/3 in 2.0s)
amazon-product-lookup: 500: no route installed (retry 1/3 in 2.0s)
amazon-product-lookup: 502: bad gateway (retry 1/3 in 2.0s)
amazon-product-lookup: 503: unavailable (retry 2/3 in 4.0s)
amazon-product-lookup: 502: bad gateway (retry 3/3 in 8.0s)
PASS  validLookupReturnsPriceAndIsNotCached (0.020s)
PASS  secondLookupIsServedFromCacheWithoutASecondUpstreamCall (0.027s)
PASS  malformedAsinIsRejectedBefore400AndNoUpstreamCall (0.076s)
PASS  unknownMarketplaceIsRejectedBefore400AndNoUpstreamCall (0.012s)
PASS  lowerCaseAsinIsNormalizedThenLookedUp (0.023s)
PASS  upstream404IsAnswerNotRetried (1.703s)
PASS  upstream429IsFreeAndRetriedUntilItSucceeds (0.093s)
PASS  upstream500IsRefundedAndRetriedExactlyOnce (0.138s)
PASS  twoConsecutive500sStopInsteadOfLoopingForever (0.101s)
PASS  upstream502And503AreRetriedUpToTheAttemptCap (0.154s)
PASS  connectionRefusedIsNeverBilledAndSurfacesAs502 (0.677s)
PASS  naPriceStaysNullNeverZero (0.025s)
PASS  concurrentLookupsOfTheSameAsinShareOneCacheSafely (0.101s)
PASS  fakeServerFailsClosedWithoutAnEnqueuedResponse (0.066s)
Tests run: 14, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.343 s
BUILD SUCCESS

This cache is per process, and so is the test suite's fake server

Running the service as several replicas behind a load balancer means each one holds its own cache, so the same ASIN can still be fetched once per replica within the TTL. That is a reasonable default for a single small service; a reader running several replicas should size the TTL around that, or swap in a shared store of their own choice - this post does not name one.

Frequently Asked Questions

Why validate with a regex and a set instead of a request-validation library?

Either works. For two fields - an ASIN regex and a marketplace set membership check - a small function avoids an extra dependency; a larger request shape is a better fit for an annotation-based validator.

Does the cache in this wrapper work across multiple replicas?

No. TtlCache is a plain in-process ConcurrentHashMap; each replica keeps its own copy. Several replicas sharing one cache need an external store, which is outside this post's scope.

Which status codes does the wrapper retry?

429 is waited out for free, a 500 is retried once since it is refunded, and 502/503 are retried up to 4 attempts total since each is billed. A 404 is never retried.

Why does a connection error reach a different code path than a billed 502/503?

Client.get() only catches ApiError (an HTTP error status) and a timeout; a raw java.net.ConnectException from a refused connection is neither, so withRetry never sees it as retryable and it propagates straight out of lookup(), uncaught.

Why does the cache need a ConcurrentHashMap here but not in a synchronous web framework?

A synchronous worker only ever runs one request at a time against its own cache dict. Ktor's Netty engine dispatches route handlers from a shared coroutine pool, so concurrent requests for the same key can run against a bare HashMap at the same time.

Bottom line: validate before any network call, cache repeat lookups for free in a ConcurrentHashMap-backed in-process TtlCache, and reuse the quickstart's own client and retry policy unchanged. Every behaviour here came from running a real Ktor application through testApplication against a fails-closed fake HTTP server - see the Kotlin quickstart for the client's own retry details and the API documentation for every endpoint.

Related Articles

Continue exploring topics related to this article.

Back to Blog

Ready to Extract Amazon Data at Scale?

Start building with SellerMagnet API today. Real-time product data, competitive pricing, and review analytics at your fingertips.

150 free API credits • No credit card required • Cancel anytime