To rate limit by IP in a Spring Boot application behind Cloudflare, do not count on
request.getRemoteAddr(): behind a proxy that is the proxy’s address, so every visitor would share
one counter. Count on the client address that Cloudflare reports in the CF-Connecting-IP header,
and read that header only when the connection really came from your proxy. In every other case fall
back to the socket address.
The code below was run on Spring Boot 4.2.0 and Java 25. Every number is an example.
Which header has the real client IP behind Cloudflare?
Cloudflare’s HTTP headers reference describes three candidates:
| Header | What it contains |
|---|---|
CF-Connecting-IP | One address: the client that connected to Cloudflare. |
X-Forwarded-For | A list. If the client already sent this header, Cloudflare appends to it, so the left side is whatever the client typed. Without an incoming header it equals CF-Connecting-IP. |
True-Client-IP | The same address as CF-Connecting-IP, on the Enterprise plan only, added by a Managed Transform. |
The same page recommends that applications read CF-Connecting-IP or True-Client-IP and not
X-Forwarded-For. A single value needs no parsing rules. If you must use X-Forwarded-For behind
one trusted proxy, take the right-most entry, the one your proxy appended, never the left-most.
Why is trusting CF-Connecting-IP blindly a vulnerability?
A header is text that the sender chooses. Cloudflare sets CF-Connecting-IP on requests that pass
through it, but anyone who can open a connection straight to your origin can send the same header
with any value. Such a caller picks a new “IP” for every request and never reaches a limit, or
picks someone else’s address and gets that person blocked.
The defences, in order:
- Do not expose the origin. Cloudflare’s guide to protecting your origin server lists the options: Cloudflare Tunnel, where the origin needs no publicly routable address, Authenticated Origin Pulls, and a firewall that only admits Cloudflare’s published IP ranges.
- Accept the header only from trusted proxy addresses. The application checks who is on the other end of the socket before it believes anything that peer says about the client.
- Fall back to the socket address whenever the peer is not a trusted proxy or the header is missing or malformed.
A safe default follows from this: ignore forwarded headers unless the deployment says explicitly that the application sits behind a trusted proxy.
How do you resolve the client IP in Java?
The resolver takes the socket address and the header value and returns the key to count on. Cidr
is a small record that parses 198.51.100.0/24 and has a contains(InetAddress) method.
InetAddress.ofLiteral (Java 22 and later) parses an IP literal and never performs a DNS lookup,
which matters for a value that arrives in a header.
public final class ClientIpResolver {
private final List<Cidr> trustedProxies;
public ClientIpResolver(List<Cidr> trustedProxies) {
this.trustedProxies = List.copyOf(trustedProxies);
}
public String rateLimitKey(String remoteAddr, String headerValue) {
InetAddress peer = InetAddress.ofLiteral(remoteAddr);
InetAddress client = peer;
if (trustedProxies.stream().anyMatch(range -> range.contains(peer))) {
InetAddress reported = parseOrNull(headerValue);
if (reported != null) {
client = reported;
}
}
return toKey(client);
}
/** IPv4: the address itself. IPv6: the /64 network it belongs to. */
private static String toKey(InetAddress address) {
byte[] bytes = address.getAddress();
if (bytes.length == 4) {
return address.getHostAddress();
}
Arrays.fill(bytes, 8, 16, (byte) 0);
try {
return InetAddress.getByAddress(bytes).getHostAddress() + "/64";
} catch (UnknownHostException e) {
throw new IllegalStateException(e);
}
}
}
parseOrNull returns null for a missing value or for anything ofLiteral rejects. The tests use
documentation ranges in place of real proxy addresses:
ClientIpResolver resolver = new ClientIpResolver(
List.of(Cidr.parse("198.51.100.0/24"), Cidr.parse("2001:db8:ffff::/48")));
@Test
void spoofedHeaderFromUntrustedAddressIsIgnored() {
assertThat(resolver.rateLimitKey("203.0.113.50", "192.0.2.1")).isEqualTo("203.0.113.50");
}
@Test
void headerFromTrustedProxyIsUsed() {
assertThat(resolver.rateLimitKey("198.51.100.7", "192.0.2.1")).isEqualTo("192.0.2.1");
}
@Test
void ipv6ClientIsReducedToItsSlash64() {
assertThat(resolver.rateLimitKey("198.51.100.7", "2001:db8:abcd:12:1111:2222:3333:4444"))
.isEqualTo("2001:db8:abcd:12:0:0:0:0/64");
}
If another reverse proxy stands between Cloudflare and the application, the socket peer is that proxy. Trust its address, and make sure it accepts traffic from Cloudflare only.
Why limit IPv6 on a /64 and not on the full address?
An IPv6 subscriber does not get one address. RFC 6177 recommends that end sites receive at least a /64 and usually more, and a single /64 holds 2^64 addresses. A limiter keyed on the full address gives one home connection a practically unlimited supply of fresh counters. Zeroing the lower 64 bits puts all of them in one bucket.
The opposite problem exists in IPv4. Offices, universities and mobile carriers put many people behind one address, so a per-IP limit that is strict enough to stop an attacker can also stop a classroom. Per-IP limiting is a coarse tool. Keep it generous, and pair it with a per-account counter wherever the request names an account.
Does Spring Boot read CF-Connecting-IP by itself?
No. Spring Boot’s forwarded-header support, described in
Running Behind a Front-end Proxy Server,
is about X-Forwarded-* and the RFC 7239 Forwarded header:
# Spring Boot 4.2
server.request.header.forwarded.strategy=web-server
# Spring Boot 4.1 and 3.x: server.forward-headers-strategy=native
With web-server (formerly native) Tomcat’s
RemoteIpValve
rewrites getRemoteAddr() from X-Forwarded-For, and only when the peer matches
server.tomcat.remoteip.internal-proxies, which by default covers private and loopback ranges.
With framework Spring’s
ForwardedHeaderFilter
does the job. It has no list of trusted proxies, and its documentation says forwarded headers must
never be allowed in from the outside. The property defaults to none outside the cloud platforms
Boot recognises.
Neither option knows Cloudflare’s header. You can point Tomcat at it with
server.tomcat.remoteip.remote-ip-header=CF-Connecting-IP and list your proxies in
internal-proxies. A resolver of your own keeps the trust rule in one class with unit tests, and
it works the same on any server.
How do you build the limiter itself?
Three algorithms cover most needs:
- Fixed window. One counter per key per window, reset when the window ends. Simple, but a burst at the end of one window and another at the start of the next lets through twice the limit.
- Sliding window. Counts requests in the last N seconds. The cheap variant keeps two counters and weights the previous window by the share of it that is still in view.
- Token bucket. Each key holds tokens that refill at a steady rate, and a request spends one. It allows short bursts up to the bucket size while holding the average rate.
The example uses the sliding window counter. For a single instance, a map is enough:
public Decision tryAcquire(String key) {
long now = clock.millis();
long index = now / windowMillis;
long elapsed = now % windowMillis;
double previousWeight = (double) (windowMillis - elapsed) / windowMillis;
boolean[] allowed = new boolean[1];
// compute() is atomic per key: check and increment cannot interleave.
windows.compute(key, (k, old) -> {
Window w = roll(old, index);
double weighted = w.current() + 1 + w.previous() * previousWeight;
allowed[0] = weighted <= limit;
return allowed[0] ? new Window(index, w.current() + 1, w.previous()) : w;
});
long retryAfter = Math.max(1, (windowMillis - elapsed + 999) / 1000);
return new Decision(allowed[0], allowed[0] ? 0 : retryAfter);
}
windows is a ConcurrentHashMap<String, Window>, Window is a record of the window index and
two counts, and roll moves the current count to previous when a new window starts. A scheduled
evictExpired() removes entries older than two windows. Without it, every address ever seen stays
in memory.
A HandlerInterceptor, registered through WebMvcConfigurer.addInterceptors, connects the two
classes:
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String key = resolver.rateLimitKey(
request.getRemoteAddr(), request.getHeader("CF-Connecting-IP"));
SlidingWindowLimiter.Decision decision = limiter.tryAcquire(key);
if (decision.allowed()) {
return true;
}
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
response.setHeader(HttpHeaders.RETRY_AFTER, String.valueOf(decision.retryAfterSeconds()));
return false;
}
The tests use an example limit of 5 requests per minute and a clock they control. They check that
the sixth request is rejected, that a burst across a window boundary does not double the limit, and
that the interceptor answers 429 with Retry-After: 60:
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.158 s -- in com.example.ratelimit.ClientIpResolverTest
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.143 s -- in com.example.ratelimit.SlidingWindowLimiterTest
[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
What changes with more than one instance?
In-process counters reset on every restart, and each instance counts separately, so two instances double everyone’s allowance. The counters have to move to a shared store, and the increment and the check must stay one atomic operation there. A clean way to get there is a store interface with two implementations, an in-process map and Redis, that share the same window arithmetic. The Redis one increments and reads inside a single Lua script, and its keys expire with their windows. If you would rather not write this, Bucket4j implements a token bucket with Redis, JDBC and JCache backends.
What should a rate-limited response look like?
Status 429 Too Many Requests, defined in
RFC 6585, with a Retry-After header
(RFC 9110) in seconds. Round it up: a
value that is too short invites a retry into the same rejection.
The RateLimit and RateLimit-Policy fields are still an
IETF Internet-Draft
(version 12 in November 2026), not an RFC, and their syntax has changed between versions. Treat
them as optional. For the body, the ProblemDetail format from
validation error responses fits a 429 as well.
Are IP addresses in rate-limit keys personal data?
Under the GDPR an IP address can identify a person, so treat the keys as personal data. Short-lived counters that expire with their window are easy to justify. Anything that lives longer, such as logs, metrics labels or block lists, should hold a truncated address or a keyed hash. The same applies to account-based keys: make the account part of a key an HMAC, so the store holds no email addresses.
Should Cloudflare rate limit before the application does?
Yes, as the first layer. Cloudflare’s rate limiting rules count requests that match an expression and block or challenge at the edge, before the traffic reaches your server. How many rules you get and how long the counting period can be depends on the plan. The edge knows nothing about your accounts or your business rules, so the application limiter stays.
Summary
- Behind Cloudflare,
getRemoteAddr()is the proxy. Count onCF-Connecting-IP. - Believe the header only when the socket peer is a trusted proxy, and keep the origin unreachable for everyone else.
- Spring Boot’s forwarded-header support handles
X-Forwarded-*andForwarded, not Cloudflare’s header. - Key IPv6 clients on their /64, and combine per-IP limits with per-account limits.
- Use a sliding window or token bucket, in memory for one instance and in a shared store for more.
- Answer 429 with
Retry-After, and do not keep raw addresses longer than the window needs.