Spring › Feature

Redis distributed rate limiting and backoff for public APIs

Enforce 1-request-per-second limits across multiple Spring Boot instances using Redis Lua scripts, Retry-After exponential backoff, and URI key masking.

Redis distributed rate limiting and backoff for public APIs

Integrating strict public Open APIs that enforce 1-request-per-second quotas across multiple Spring Boot instances quickly breaks naive in-memory rate limiters. In this post, I walk through a three-layer defense built in production: an atomic Redis Lua request gate, cluster-wide Retry-After cooldowns with exponential backoff, and URI template masking to keep query-string API keys out of logs.

Built with Spring Boot, Kotlin, Java 21 HttpClient, Spring RestClient, and Redis.


Why strict public Open APIs are hard to integrate

While building a court-ruling ingestion and AI summarization backend (demo-backend-server), I integrated Korea’s National Law Information Center Open API to sync tens of thousands of precedent records daily. Public data APIs come with four constraints that break standard HTTP client setups:

  1. Strict 1-request-per-second quotas: Most public endpoints enforce roughly one request per second per IP or API key (OC). Exceeding that ceiling triggers 429 Too Many Requests—or worse, a temporary key suspension.
  2. Multi-instance scale-out: In-memory limiters like Guava RateLimiter or local Bucket4j buckets work on a single JVM, but once you run multiple Kubernetes pods or parallel batch workers, each node fires requests independently and blows past the shared quota.
  3. Flaky 5xx responses and non-JSON error payloads: Upstream maintenance or traffic spikes frequently return 502 Bad Gateway, 503 Service Unavailable, HTML maintenance pages via 302 redirects, or unexpectedly huge error bodies.
  4. Query-parameter secret keys (?OC=...): Many public APIs require passing the secret key in the URL query string instead of an Authorization header. Plain string interpolation leaks that secret into framework debug logs, reverse-proxy access logs, APM traces, and exception stack traces.

To handle all four issues reliably, I built three layers: an atomic Redis request gate, Retry-After exponential backoff with cluster-wide cooldown propagation, and URI template masking with exception sanitization.

Console log showing 1-second request spacing enforced by the Redis global gate Figure 1. Integration test log showing concurrent requests across multiple instances spaced cleanly at 1-second intervals by the Redis global gate.


1. Cross-instance spacing with an atomic Redis Lua gate

No matter how many application instances or batch threads run concurrently, the cluster as a whole must wait at least one full interval (1,000ms) between outgoing API calls. I implemented LawApiRequestGate using Redis key TTLs and atomic Lua scripts.

Atomic Lua slot acquisition

Running the check-and-set inside a single Lua script eliminates race conditions between pods:

1
2
3
4
5
6
7
-- SLOT: return remaining TTL if a slot is active; otherwise reserve a new slot
local ttl = redis.call('PTTL', KEYS[1])
if ttl > 0 then
    return ttl
end
redis.call('SET', KEYS[1], '1', 'PX', ARGV[1])
return 0
  • PTTL KEYS[1] checks the remaining millisecond lifetime of the slot key.
  • If ttl > 0, another instance already holds the current window, so Redis returns the exact wait time in milliseconds.
  • If the key is absent or expired, Redis sets it with PX interval (for example, 1000ms) and returns 0, granting immediate permission to call the API.

Implementing LawApiRequestGate

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
// src/main/kotlin/com/example/server/judgment/application/LawApiRequestGate.kt
package com.example.server.judgment.application

import com.example.server.judgment.LawApiProperties
import org.springframework.beans.factory.annotation.Value
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.data.redis.core.script.DefaultRedisScript
import org.springframework.stereotype.Component
import java.time.Duration

/** Shares outgoing request spacing across multiple instances and batch workers via Redis. */
@Component
class LawApiRequestGate(
    private val redis: StringRedisTemplate,
    private val properties: LawApiProperties,
    @Value("\${spring.profiles.active:default}") private val environment: String,
) {
    private val key: String get() = "demo-app:$environment:law-api:request-slot"

    fun await() {
        var waited = 0L
        while (true) {
            val delay = try {
                redis.execute(SLOT, listOf(key), properties.requestInterval.toMillis().toString())
                    ?: throw LawPrecedentException("Unable to check precedent API request interval.")
            } catch (e: org.springframework.dao.DataAccessException) {
                throw LawPrecedentException("Failed to enforce API rate limit. Check Redis health.")
            }
            if (delay == 0L) return
            if (waited + delay > 30_000) {
                throw LawPrecedentException("Exceeded 30-second wait cap for precedent API slot.")
            }
            Thread.sleep(delay)
            waited += delay
        }
    }

    /** Propagates a 429 cooldown to all instances without shortening any existing longer wait. */
    fun defer(duration: Duration) {
        try {
            redis.execute(DEFER, listOf(key), duration.toMillis().coerceAtLeast(1).toString())
        } catch (e: org.springframework.dao.DataAccessException) {
            throw LawPrecedentException("Failed to store API cooldown in Redis. Check Redis health.")
        }
    }

    companion object {
        private val SLOT = DefaultRedisScript("""
            local ttl = redis.call('PTTL', KEYS[1])
            if ttl > 0 then return ttl end
            redis.call('SET', KEYS[1], '1', 'PX', ARGV[1])
            return 0
        """.trimIndent(), Long::class.java)

        private val DEFER = DefaultRedisScript("""
            local delay = tonumber(ARGV[1])
            if redis.call('PTTL', KEYS[1]) < delay then
                redis.call('SET', KEYS[1], '1', 'PX', delay)
            end
            return 1
        """.trimIndent(), Long::class.java)
    }
}
sequenceDiagram
    autonumber
    participant Node1 as Instance Node-1
    participant Node2 as Instance Node-2
    participant Redis as Redis Gate
    participant API as Public Open API
    Node1->>Redis: execute(SLOT, key, 1000ms)
    Redis-->>Node1: delay = 0ms (slot acquired)
    Node1->>API: GET /DRF/lawSearch.do
    Note over Node2: 200ms later
    Node2->>Redis: execute(SLOT, key, 1000ms)
    Redis-->>Node2: delay = 800ms (busy)
    Node2->>Node2: Thread.sleep(800ms)
    API-->>Node1: 200 OK
    Node2->>Redis: execute(SLOT, key, 1000ms)
    Redis-->>Node2: delay = 0ms (slot acquired)
    Node2->>API: GET /DRF/lawService.do

Every call goes through await() first. If Redis returns delay > 0, the thread sleeps for that exact remainder and retries, capped at 30 seconds (30_000ms) so workers never hang indefinitely.

When Redis throws a DataAccessException, LawApiRequestGate fails closed by throwing a domain exception instead of falling back to unthrottled requests. Failing open against a strict public API risks getting your IP or key banned during a brief Redis hiccup.


2. Handling 429 and 5xx with Retry-After and cluster cooldowns

Even with a 1-second gate, upstream congestion can still trigger 429 Too Many Requests or 5xx errors. Retrying locally with a fixed sleep has two flaws:

  • Cross-node 429 cascades: While Node-1 sleeps after a 429, Node-2 keeps firing requests into the same throttled upstream.
  • Ignoring upstream instructions: Ignoring a Retry-After: 10 header and hammering the endpoint early increases the chance of a longer block.

Extending the cluster cooldown (defer)

When any instance receives a 429, it calls gate.defer(duration) to extend the Redis slot key’s TTL for the entire cluster:

1
2
3
4
5
6
-- DEFER: extend TTL only when the new cooldown is longer than the remaining TTL
local delay = tonumber(ARGV[1])
if redis.call('PTTL', KEYS[1]) < delay then
    redis.call('SET', KEYS[1], '1', 'PX', delay)
end
return 1

Every pod immediately sees the extended TTL on its next await() call and pauses until the upstream window clears.

Console log showing Retry-After parsing and cluster-wide cooldown backoff Figure 2. Console log when a 429 Too Many Requests arrives. The client parses Retry-After and triggers defer() in Redis to pause all instances together.

Exponential backoff and Retry-After parsing

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
// src/main/kotlin/com/example/server/judgment/application/LawPrecedentClient.kt (excerpt)
private fun request(path: String, parameters: Map<String, Any>, check: () -> Unit): String {
    if (properties.oc.isBlank()) throw LawPrecedentException("LAW_API_OC credential is not configured.")
    repeat(properties.maxAttempts) { attempt ->
        check()
        beforeRequest() // calls gate::await for 1-second spacing
        check()
        try {
            return client.get().uri { uri ->
                uri.path("/DRF/$path").queryParam("OC", "{oc}").queryParam("target", "prec").queryParam("type", "JSON")
                parameters.keys.forEach { key -> uri.queryParam(key, "{$key}") }
                uri.build(parameters + mapOf("oc" to properties.oc))
            }.accept(MediaType.APPLICATION_JSON).exchange { _, response ->
                val status = response.statusCode.value()
                if (status != 200) throw HttpFailure(status, response.headers.getFirst("Retry-After"))
                val bytes = response.body.readNBytes(properties.maxResponseBytes + 1)
                if (bytes.size > properties.maxResponseBytes) throw LawPrecedentException("Precedent API response exceeded size limit.")
                if (bytes.isEmpty()) throw LawPrecedentException("Precedent API returned an empty response.")
                String(bytes, response.headers.contentType?.charset ?: Charsets.UTF_8)
            }
        } catch (e: HttpFailure) {
            val retryAfter = retryAfter(e.retryAfter)
            // Pick the larger of exponential backoff (1s, 2s, 4s...) or server-requested Retry-After
            val delay = maxOf(Duration.ofSeconds(1L shl attempt), retryAfter)
            if (e.status == 429) cooldown(delay.coerceAtMost(Duration.ofDays(1))) // calls gate::defer
            if ((e.status != 429 && e.status !in 500..599) || attempt + 1 == properties.maxAttempts) {
                throw LawPrecedentException("Precedent API request failed: HTTP ${e.status} (attempt ${attempt + 1}).")
            }
            if (retryAfter > Duration.ofSeconds(30)) {
                throw LawPrecedentException("Retry-After exceeded 30-second limit. Deferring to the next scheduled run.")
            }
            pause(delay)
        } catch (e: ResourceAccessException) {
            if (Thread.currentThread().isInterrupted) throw InterruptedException("Precedent API call interrupted.")
            if (attempt + 1 == properties.maxAttempts) {
                throw LawPrecedentException("Precedent API network call failed (attempt ${attempt + 1}).")
            }
            pause(Duration.ofSeconds(1L shl attempt))
        } catch (e: RestClientException) {
            throw LawPrecedentException("Unable to read precedent API response.")
        }
    }
    error("maxAttempts is validated to be positive at startup.")
}

private fun retryAfter(value: String?): Duration {
    if (value == null) return Duration.ZERO
    if (value.matches(Regex("\\d+")) && value.toLongOrNull() == null) return Duration.ofDays(1)
    value.toLongOrNull()?.let { return Duration.ofSeconds(it.coerceAtLeast(0)) }
    return try {
        // Parse RFC 1123 HTTP-date format (e.g., Wed, 21 Oct 2026 07:28:00 GMT)
        Duration.between(Instant.now(), ZonedDateTime.parse(value, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant()).coerceAtLeast(Duration.ZERO)
    } catch (e: java.time.format.DateTimeParseException) { Duration.ZERO }
}

Three rules govern the retry loop:

  1. Respect the longer wait: maxOf(Duration.ofSeconds(1L shl attempt), retryAfter) obeys Retry-After when the server sends one, and falls back to 1s → 2s → 4s exponential backoff otherwise.
  2. Bail out on long cooldowns: If the server asks for Retry-After: 3600, holding a worker thread for an hour makes no sense. Anything over 30 seconds records the Redis cooldown and aborts the current run so the next scheduled run resumes from the saved batch checkpoint.
  3. Fail fast on 4xx errors: 400, 401, and 403 won’t heal on retry. Only 429, 5xx, and network I/O errors (ResourceAccessException) enter the backoff loop.

3. Hardening RestClient timeouts, redirects, and payload size

I configured Spring’s RestClient on top of Java 21’s HttpClient with explicit guards against hanging sockets and runaway payloads. For deeper tuning of RestClient pools and timeouts, see my RestClient timeout and connection pool guide.

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
// src/main/kotlin/com/example/server/judgment/LawApiConfig.kt
package com.example.server.judgment

import com.example.server.judgment.application.LawPrecedentClient
import com.example.server.judgment.application.LawApiRequestGate
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.client.JdkClientHttpRequestFactory
import org.springframework.web.client.RestClient
import tools.jackson.databind.json.JsonMapper
import java.net.http.HttpClient

@Configuration
class LawApiConfig {
    @Bean
    fun lawPrecedentClient(
        builder: RestClient.Builder,
        properties: LawApiProperties,
        mapper: JsonMapper,
        gate: LawApiRequestGate
    ): LawPrecedentClient {
        val http = HttpClient.newBuilder()
            .connectTimeout(properties.connectTimeout) // 3s
            .followRedirects(HttpClient.Redirect.NEVER) // Disable automatic redirects
            .build()
        val factory = JdkClientHttpRequestFactory(http).apply {
            setReadTimeout(properties.readTimeout) // 10s
        }
        val client = builder.clone()
            .baseUrl("https://www.law.go.kr")
            .requestFactory(factory)
            .build()
        return LawPrecedentClient(client, mapper, properties, gate::await, cooldown = gate::defer)
    }
}
  • Disable redirects (Redirect.NEVER): Public portals often redirect to an HTML maintenance notice with 302 Found. Rejecting redirects immediately avoids wasting bandwidth and feeding HTML into Jackson.
  • Separate connect and read timeouts: Keeping connectTimeout at 3 seconds and readTimeout at 10 seconds isolates TCP handshake stalls from slow response bodies.
  • Bound response bytes (readNBytes): Reading at most maxResponseBytes + 1 (default 16 MB) prevents a malformed or unexpectedly huge payload from triggering an OutOfMemoryError.

4. Preventing query-string API key leaks in logs and errors

Interpolating a query-parameter secret directly into a URL string is one of the easiest ways to leak credentials:

1
2
3
// Dangerous: interpolates the secret directly into the URL string
val url = "https://www.law.go.kr/DRF/lawSearch.do?OC=${properties.oc}&target=prec"
restClient.get().uri(url)...

With direct string interpolation, RestClient debug logs, APM instrumentation, and exception messages record the raw secret in plain text.

Security test output confirming masked API keys in exception logs Figure 3. Security test confirming that URI template masking and sanitized exceptions keep the OC key and upstream error bodies out of logs and database error records.

Parameterize with URI templates

Declare {oc} as a URI template variable and bind the secret map only when building the request:

1
2
3
4
5
6
7
8
9
// Safe: binds the secret via URI template variables
client.get().uri { uri ->
    uri.path("/DRF/$path")
        .queryParam("OC", "{oc}") // Template placeholder
        .queryParam("target", "prec")
        .queryParam("type", "JSON")
    parameters.keys.forEach { key -> uri.queryParam(key, "{$key}") }
    uri.build(parameters + mapOf("oc" to properties.oc))
}

Framework metrics and template-aware logging record /DRF/lawSearch.do?OC={oc}&target=prec instead of the secret value.

Sanitize exceptions and drop raw causes

Upstream 403 responses sometimes echo the rejected key back in the response body (Invalid key [OC=xxx]). Wrapping that body or the low-level HTTP exception as the cause of your domain exception leaks it right back into logs and job_run_errors.

In LawPrecedentClient, I enforce three rules and lock them down with a unit test:

  1. Never include the URL, API key, or raw upstream body in exception messages.
  2. Throw clean domain exceptions with no underlying cause (hasNoCause()) so socket and client internals stay hidden.
  3. Persist only sanitized messages to job_run_errors.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// src/test/kotlin/com/example/server/judgment/LawPrecedentClientTest.kt
@Test
fun `does not retry auth or redirect errors and strips secrets from exceptions`() {
    val statuses = listOf(HttpStatus.FORBIDDEN, HttpStatus.MOVED_PERMANENTLY)
    statuses.forEach { status ->
        server.expect { }.andRespond(withStatus(status).body("OC=secret_key_12345, upstream error details"))
    }
    for (status in statuses) {
        assertThatThrownBy { client().detail(12) }
            .isInstanceOf(LawPrecedentException::class.java)
            .hasMessageContaining("HTTP ${status.value()}")
            .hasMessageNotContaining("OC=")
            .hasMessageNotContaining("secret_key_12345")
            .hasNoCause() // Prevent low-level stack leak
    }
}

5. Verifying cross-instance spacing with a concurrency test

To verify the Lua scripts under contention, I spin up two independent LawApiRequestGate instances backed by Redis and fire four concurrent threads against a 200ms test interval:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Test
fun `two independent gates share Redis request spacing under concurrent load`() {
    val env = "verify-${UUID.randomUUID()}"
    val key = "demo-app:$env:law-api:request-slot"
    val properties = LawApiProperties(requestInterval = Duration.ofMillis(200))
    val gates = listOf(LawApiRequestGate(redis, properties, env), LawApiRequestGate(redis, properties, env))
    val pool = Executors.newFixedThreadPool(4)
    val ready = CountDownLatch(1)
    try {
        val times = (0..3).map { i -> pool.submit<Long> { ready.await(); gates[i % 2].await(); System.nanoTime() } }
        ready.countDown()
        val completed = times.map { it.get(5, TimeUnit.SECONDS) }.sorted()

        // 4 requests at 200ms spacing must span at least 3 intervals (~600ms)
        assertThat(Duration.ofNanos(completed.last() - completed.first()).toMillis()).isGreaterThanOrEqualTo(550)

        // Verify defer() extends TTL and never shortens an existing longer cooldown
        gates[0].defer(Duration.ofSeconds(1))
        val ttl = redis.getExpire(key, TimeUnit.MILLISECONDS)!!
        gates[1].defer(Duration.ofMillis(200)) // Shorter request must be ignored
        assertThat(ttl).isGreaterThan(800)
    } finally { pool.shutdownNow(); redis.delete(key) }
}

In production batch runs with this gate active, concurrent workers serialize cleanly at 1-second intervals and 429 blocks dropped to 0.0%.


Trade-offs and checklist

A fixed-slot Redis gate works well for low-throughput, strict-interval APIs (1–5 RPS). Don’t use a busy-wait Thread.sleep() loop on request-handling web threads for high-traffic user-facing endpoints—blocking servlet threads under load will exhaust your Tomcat pool. For high-RPS APIs, use a token-bucket algorithm or push external calls onto an async queue.

Before shipping a distributed rate limiter for a public API, check these four items:

  • Make slot acquisition atomic: Use a single Redis Lua script (PTTL + SET PX) rather than separate GET and SET calls.
  • Propagate 429 cooldowns globally: Extend the shared Redis TTL with defer() so every instance backs off together, and never shorten a longer TTL.
  • Cap wait times and payload sizes: Abort early when Retry-After exceeds your worker budget (e.g., 30s) and bound response reads with readNBytes.
  • Test secret masking: Assert hasMessageNotContaining("OC=") and hasNoCause() in CI so future refactors can’t accidentally re-introduce credential leaks.
This post is licensed under CC BY 4.0 by the author.