<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alikhan Zhomartov on Medium]]></title>
        <description><![CDATA[Stories by Alikhan Zhomartov on Medium]]></description>
        <link>https://medium.com/@alikhansoftwareengineer?source=rss-8b1ff6841673------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8aMlHht7YUe5S_SjgCOAZw.jpeg</url>
            <title>Stories by Alikhan Zhomartov on Medium</title>
            <link>https://medium.com/@alikhansoftwareengineer?source=rss-8b1ff6841673------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 13:15:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alikhansoftwareengineer/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Goodbye WebFlux: Building a 100k Connection Chess Server with Imperative Java and Virtual Threads]]></title>
            <link>https://medium.com/@alikhansoftwareengineer/goodbye-webflux-building-a-100k-connection-chess-server-with-imperative-java-and-virtual-threads-59211f09eb06?source=rss-8b1ff6841673------2</link>
            <guid isPermaLink="false">https://medium.com/p/59211f09eb06</guid>
            <dc:creator><![CDATA[Alikhan Zhomartov]]></dc:creator>
            <pubDate>Thu, 15 Jan 2026 22:42:30 GMT</pubDate>
            <atom:updated>2026-01-15T23:33:12.943Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HjA_qLryMBEPThQ4ETl_iA.png" /></figure><p>For years, Java developers faced a harsh dilemma: either write simple imperative code and hit OS thread limits, or descend into “reactive hell” with Project Reactor or WebFlux to scale to hundreds of thousands of connections. But Project Loom changed the game.</p><p>In this article, I’ll show you how to build an architecture for an online chess service using modern Java (version 25) that handles thousands of WebSocket connections without writing a single Mono or Flux.</p><p><strong>Skip the theory:</strong> If you’re here for the implementation, the full source code is available on <a href="https://github.com/AlikhanZhomartov/chess-backend.git">GitHub</a>. Dive in and see how it scales.</p><h3>TL;DR (The Gist)</h3><ul><li><strong>Problem</strong>: The reactive approach (WebFlux/Reactor) is complex to develop and debug, while classic thread-per-connection doesn’t scale to 100k+ connections due to the overhead of OS threads.</li><li><strong>Solution</strong>: Combining Netty (for efficient I/O) with Virtual Threads (for simple imperative business logic).</li><li><strong>Key Innovation</strong>: The Virtual Actor pattern — how to maintain strict message ordering within a session without blocking Netty threads and without using synchronized.</li><li><strong>Result</strong>: Clean “linear” code that’s easy to read, with performance on par with high-load reactive systems.</li></ul><h3>Disclaimer</h3><p><strong>Important</strong>: This project is not a production-ready, “out-of-the-box” solution for launching a commercial chess service. It’s an architectural exploration and demonstration of how modern Java capabilities (Project Loom) allow you to elegantly move away from “reactive hell” to understandable imperative style without sacrificing performance. Some aspects in the code are intentionally simplified (for example, game engine logic) to focus on network interaction and concurrency.</p><h3>The Architectural Landscape</h3><p>Before diving into code, let’s get a bird’s-eye view of our backend. I split the system into two key microservices to separate network load from heavy business logic:</p><h4>1. Gateway (Socket Service) — Our Main Character</h4><p>This is the entry point for all players. Built on Netty, which gives us complete control over the network stack. Its main responsibilities:</p><ul><li>Maintaining thousands of active WebSocket sessions</li><li>Player authentication via JWT directly in the Netty pipeline</li><li>Command routing: the service receives a player’s move, validates who they are, and forwards the request</li></ul><h4>2. Game Brain Service — The System’s Intelligence</h4><p>This is the computational service where all the chess magic lives (or will live): move validation, checkmate detection, and chess engine operations. Currently it’s a stub that always says “move allowed,” but architecturally it’s ready for production loads.</p><h4>3. The Nervous System: gRPC and NATS</h4><p>For service-to-service communication, I chose two different tools for different tasks:</p><p><strong>gRPC (Request-Response)</strong>: When a player makes a move, the Socket service makes a synchronous call (from the code’s perspective) to the Brain service. Thanks to virtual threads, we can afford to simply wait for the response without blocking the system.</p><p><strong>NATS (Broadcasting)</strong>: Once a move is accepted, we need to instantly notify the opponent and all spectators. The event is published to NATS. Socket services subscribe to their game topics and “push” updates to the appropriate client WebSockets.</p><h3>A Bit of Theory: Why WebSockets Are a “Hard Nut to Crack”</h3><p>If a regular HTTP request is a brief “hello-goodbye,” then a WebSocket is a full-fledged, long-running “phone conversation.” And that’s where the main architectural trap lies.</p><h4>The Magic of Numbers: Are 10, 000 Connections a Lot or a Little?</h4><p>Let’s compare two approaches with 10,000 active players:</p><p><strong>Classic Approach (Thread-per-connection)</strong>: Imagine a standard servlet container (like Tomcat). To handle 10,000 players, it needs 10,000 OS threads (Platform Threads).</p><ul><li><strong>Memory</strong>: By default, one thread’s stack in the JVM takes ~1 MB. Total: 10 GB of RAM wasted just for these threads to exist. And that’s before the first pawn moves to e4.</li><li><strong>CPU</strong>: The processor goes crazy trying to context switch between 10,000 threads. System efficiency drops nearly to zero.</li></ul><p><strong>Our Approach (Netty + Event Loop)</strong>: Netty doesn’t wait for data from a specific client. In our ChessSocketServer, we use MultiThreadIoEventLoopGroup.</p><ul><li>The same 10,000 connections are served by just 8–16 threads (depending on your CPU cores)</li><li><strong>Memory</strong>: We spend resources only on actual data in network buffers, not on empty stacks of sleeping threads</li></ul><h4>Why Netty Is Still King</h4><p>Netty is the perfect foundation. It handles all the “dirty work” with bytes, letting us assemble a processing pipeline like LEGO blocks. In our project, you can see this in the setupPipeline method: from HTTP decoding to JWT verification and game command processing.</p><pre> private static void setupPipeline(SocketChannel ch, GameService gameService, SessionManager sessionManager, JwtService jwtService) {<br>        ch.pipeline()<br>                .addLast(new HttpServerCodec())<br>                .addLast(new HttpObjectAggregator(65536))<br>                .addLast(new JwtAuthHandler(jwtService))<br><br>                .addLast(new IdleStateHandler(60, 30, 0, TimeUnit.SECONDS))<br>                .addLast(new WebSocketServerProtocolHandler(&quot;/game&quot;, null, true))<br>                .addLast(new WebSocketFrameAggregator(65536))<br><br>                .addLast(new HeartbeatHandler())<br>                .addLast(new SessionLifecycleHandler(gameService, sessionManager))<br>                .addLast(new GamePlayHandler(gameService))<br><br>                .addLast(new GlobalExceptionHandler());<br>    }</pre><p>But Netty has a “catch”: Its Event Loop threads are strictly forbidden to block. Make one heavy database call or gRPC request inside a handler, and you’ve “hung” thousands of other players whose sockets are served by that same thread.</p><p>This is where “reactive hell” used to begin: you had to wrap everything in Mono, Flux, or CompletableFuture. We took a different approach. We said: “Let Netty handle networking, and let Virtual Threads handle business logic.”</p><h3>The Magic of Virtual Threads: Code That Can Wait (and When It Should)</h3><p>The main problem with any Gateway service is constant waiting. It waits for socket data, waits for gRPC backend responses, waits for NATS confirmations.</p><p>Previously, “waiting” meant an expensive OS thread just hanging in memory. In reactive Java, you had to break logic into callback chains. With Virtual Threads (Project Loom), we got “cheap” threads managed by the JVM itself.</p><h4>When Are Virtual Threads a Savior, and When a Trap?</h4><p>Important to understand: virtual threads aren’t all-powerful. They’re designed for tasks that don’t block the OS thread (Carrier Thread) for long. If you run Bitcoin mining in a VT, you’ll just kill all performance.</p><p>Where’s the boundary of “too long”? In our project, we follow this engineering logic:</p><ul><li><strong>Micro-tasks (&lt; 1 ms)</strong>: Do directly in the virtual thread. This includes parsing incoming JSON commands. The cost of context switching and inevitable CPU cache misses (L1/L2) when moving to another pool would cost more than the work itself.</li><li><strong>Medium tasks (1–10 ms)</strong>: Gray area. Depends on load.</li><li><strong>Heavy tasks (&gt; 10 ms)</strong>: If the task is purely computational (e.g., deep chess position analysis by the engine), it must be moved to a separate Platform Threads pool. Otherwise, you’ll “pin” the virtual thread to a system thread, and the magic of scalability disappears.</li></ul><h4>How This Looks in Code</h4><p>In our socket-service, we use an executor based on virtual threads. Thanks to this, move processing looks like regular “boring” imperative code:</p><pre>@Override<br>protected void process(ChannelHandlerContext ctx, TextWebSocketFrame frame) {<br>    try {<br>        String json = frame.text();<br>        // Parse JSON right here. It&#39;s fast (microseconds), <br>        // so we don&#39;t waste resources on context switching.<br>        var message = ResponseUtils.getMapper().readValue(json, ClientRequest.class);<br><br>        // Then we go to gRPC. If the backend request takes 50ms, <br>        // the virtual thread simply &quot;sleeps,&quot; freeing OS resources.<br>        dispatch(ctx, message); <br>    } catch (Exception e) {<br>        handleException(ctx, e, message);<br>    }<br>}</pre><p><strong>Bottom line</strong>: We get WebFlux-level performance but write code top-to-bottom like in the good old days. We’re not afraid of blocking gRPC or NATS calls because the JVM efficiently manages resources itself.</p><h3>Virtual Actor: Bringing Order to the World of Chaos</h3><p>In classic Netty, we have a “free” guarantee: all events for one specific connection (channel) are processed in the same EventLoop thread. This means if a player sends “Move A” and then “Move B,” they’re guaranteed to be processed strictly in order.</p><h4>The Problem: The Cost of VT Freedom</h4><p>As soon as we decided to use the power of Virtual Threads, we encountered a side effect. When a Netty thread receives a message and simply “tosses” it into the virtual thread pool (executor.submit(…)), it instantly loses control over it.</p><p>Imagine:</p><ul><li>“Move A” arrives. We create a virtual thread to process it.</li><li>A millisecond later “Move B” arrives. We create a second virtual thread.</li><li>The JVM scheduler might decide the second thread should execute slightly faster, or the first thread might “stumble” on a gRPC request.</li><li><strong>Result</strong>: “Move B” might apply before “Move A.” In chess, that’s catastrophic — you’re trying to move a piece that isn’t there yet.</li></ul><h4>Solution: The Virtual Actor Pattern</h4><p>To restore strict ordering while not blocking Netty threads, we implemented our own lightweight Virtual Actor Handler.</p><p>The idea is simple: each connection is an “Actor” with its own mailbox.</p><p>Here’s how it works under the hood:</p><ol><li><strong>Mailbox (Queue)</strong>: Inside the handler lives a high-performance non-blocking queue MpscUnboundedArrayQueue</li><li><strong>Writing</strong>: When Netty receives a message, it doesn’t create a new thread but simply puts the task in this queue and calls scheduleExecution()</li><li><strong>Exclusive Executor</strong>: The scheduleExecution method uses AtomicBoolean (isRunning) to guarantee: at any moment, messages from the queue are processed by only one virtual thread</li></ol><pre>private void drainLoop() {<br>    try {<br>        Runnable task;<br>        // We take tasks from the queue one by one<br>        while ((task = mailbox.poll()) != null) {<br>            try {<br>                task.run(); // Execute our imperative code (gRPC, logic)<br>            } catch (Throwable t) {<br>                log.error(&quot;Actor task execution failed&quot;, t);<br>            }<br>        }<br>    } finally {<br>        // Once the queue is empty, mark the actor as free<br>        isRunning.set(false);<br>        // Check in case a message arrived during completion<br>        if (!mailbox.isEmpty()) {<br>            scheduleExecution();<br>        }<br>    }<br>}</pre><h4>Why This Is Brilliant (and Simple)</h4><ul><li><strong>Thread-safety out of the box</strong>: Since drainLoop processes tasks sequentially, you don’t need synchronized, Locks, or AtomicInteger inside your game logic. The entire GamePlayHandler works in single-threaded mode relative to a specific game.</li><li><strong>Scalability</strong>: If we have 100,000 connections, we’ll have 100,000 queues. But only those that actually have messages at the moment will be working (occupying real CPU threads).</li><li><strong>No Netty blocking</strong>: The Netty thread only puts a task in the queue (nanosecond operation) and goes to serve other sockets.</li></ul><p>Thus, we got the perfect combination: EventLoop efficiently delivers messages, while Virtual Actors based on virtual threads imperatively process them while maintaining perfect order.</p><h3>Bonus #1: When Virtual Threads Turn Into a Pumpkin</h3><p>Many think that with Java 21+ you can simply replace all ThreadPoolExecutor with Executors.newVirtualThreadPerTaskExecutor() and you’re golden. This is a dangerous misconception.</p><p>In our project, we clearly separated where we use VT and where we use good old platform threads.</p><h4>CPU-bound Tasks: Why We Kept Fixed Pool in Brain Service</h4><p>If you look at ChessBrainServer, you’ll see the gRPC server uses Executors.newFixedThreadPool(CORES). Why not virtual threads?</p><p><strong>The Pinning Problem</strong>: A virtual thread is just an object in the heap that executes on a real “carrier thread.” If your task is heavy computation (chess move validation, position enumeration), the virtual thread won’t encounter blocking points (I/O, locks) and won’t “release” the system thread.</p><p><strong>Resource Starvation</strong>: Virtual threads don’t know how to actively share CPU resources under purely computational load. Platform threads are managed by the OS scheduler, which forcibly interrupts one thread’s execution to let another work.</p><p><strong>The Perfect Formula</strong>: For the chess “engine,” we allocated exactly as many threads as processor cores (availableProcessors). This guarantees we use the CPU at 100% without wasting time on useless context switching between thousands of virtual entities.</p><h4>Can You Combine Them? (Spoiler: You Should)</h4><p>In the future, our Brain service might start hitting databases or cache. In that case, we’ll introduce a hybrid model:</p><ul><li>VT accepts the gRPC request and handles all I/O operations (loading game history, writing logs)</li><li>Platform Threads Pool takes only the “heavy” math (position analysis)</li></ul><p>This combination allows us not to block incoming requests during computations while guaranteeing the “brain” doesn’t consume all JVM scheduler memory.</p><h3>Bonus #2: Zero-Parsing — Pushing Bytes at Full Speed</h3><p>When one player makes a move, the socket-service must broadcast it to all participants via NATS. Here we applied another “advanced” optimization.</p><p>Usually developers do this:</p><ol><li>Receive JSON from NATS</li><li>Deserialize it into a Java object (DTO)</li><li>Re-serialize that object into JSON to send to the socket</li></ol><p>We threw out this extra step. Since game-brain-service already formed valid JSON, our Gateway works in transparent proxy mode:</p><ol><li>We take raw bytes from NATS</li><li>Directly wrap them in TextWebSocketFrame via Unpooled.wrappedBuffer(rawData)</li><li>Send to the socket</li></ol><p><strong>The benefit</strong>: We don’t spend a single CPU cycle on text parsing and don’t create extra objects in the Heap that would later need to be cleaned up by the Garbage Collector. Our service simply “transfers” bytes from one pipe to another at the speed of light.</p><h3>Conclusion</h3><p>Modern Java allows us to be flexible. We used Netty for networking, Virtual Threads for asynchronous imperative code in the gateway, and Platform Threads for heavy computations where it’s truly needed.</p><p>This isn’t just a “trendy stack” — it’s an architecturally sound design that lets you write simple code capable of handling hundreds of thousands of players.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59211f09eb06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Routing in Spring Cloud Gateway: Balancing Velocity and Reliability.]]></title>
            <link>https://medium.com/@alikhansoftwareengineer/dynamic-routing-in-spring-cloud-gateway-balancing-velocity-and-reliability-21bc2922ef3b?source=rss-8b1ff6841673------2</link>
            <guid isPermaLink="false">https://medium.com/p/21bc2922ef3b</guid>
            <dc:creator><![CDATA[Alikhan Zhomartov]]></dc:creator>
            <pubDate>Mon, 05 Jan 2026 18:53:48 GMT</pubDate>
            <atom:updated>2026-01-05T20:00:02.079Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*M3TDRp78VZe2YOXMPlq37A.png" /></figure><p><strong>Skip the theory:</strong> If you’re here for the implementation, the full source code is available on <a href="https://github.com/AlikhanZhomartov?tab=repositories">GitHub</a>. Dive in and see how it scales.</p><p>Modern microservice ecosystems demand a level of flexibility that standard operational patterns often struggle to provide. Feature flagging, A/B testing, and dynamic load shedding require API Gateway configurations to change frequently.</p><p>Spring Cloud Gateway (SCG) is a powerful tool, but achieving <strong>Zero Downtime</strong> updates while modifying routes presents unique engineering challenges.</p><p>In this deep dive, we explore the mechanics of configuration updates, analyze why Kubernetes orchestration isn’t a silver bullet for availability, and dissect the performance costs of the standard Spring Cloud Bus. Finally, we propose a lightweight, event-driven alternative based on Redis.</p><h3>The Illusion of “Simple” Static Config</h3><p>Teams often start with the simplest approach: hardcoding routes in application.yml or Kubernetes ConfigMaps.</p><ul><li><strong>The Proponent’s Argument:</strong> “Kubernetes handles zero-downtime via orchestration.”</li><li><strong>The Skeptic’s Reality:</strong> “Orchestration is never free.”</li></ul><h4>The Real Cost of a Rolling Update</h4><p>Let’s examine the physical sequence of events during a ConfigMap change:</p><ol><li>A new pod (<strong>Pod V2</strong>) starts.</li><li>K8s waits for the Readiness Probe.</li><li>Traffic shifts to Pod V2.</li><li><strong>Pod V1</strong> receives SIGTERM.</li><li>Pod V1 enters “Connection Draining” mode and eventually terminates.</li></ol><p>While theoretically sound, this introduces significant risks in High Load environments:</p><ul><li><strong>Connection Draining Issues:</strong> SCG runs on Netty. Unlike Tomcat, gracefully terminating long-lived connections (WebSocket, SSE) is non-trivial. Even with server.shutdown: graceful, forcing a disconnect upon SIGKILL (timeout) affects user experience.</li><li><strong>JIT Warmup Penalty:</strong> The new Pod V2 is “cold.” The JVM requires time to compile hot paths. If production traffic hits it instantly, latency spikes occur immediately.</li></ul><p><strong>The “Inflection Point” Mathematics</strong></p><p>When does static configuration become a bottleneck? It is a function of three variables:</p><p>Cost = f(RPS, ChurnRate, ConnectionLongevity)</p><h4>Scenario A — Low Frequency</h4><p><strong>5–10 changes per week</strong></p><p><strong>Verdict:</strong> Stick to Static<br> The complexity of dynamic routing isn’t justified. Rolling updates are sufficient.</p><h4>Scenario B — Medium Frequency</h4><p><strong>1–5 changes per hour</strong></p><p><strong>Verdict:</strong> Grey Zone<br> If a p99 latency spike of <strong>~500 ms</strong> is acceptable, static routing might still work.</p><h4>Scenario C — High Frequency</h4><p><strong>CI/CD, Canary releases, Dynamic Rate Limiting</strong></p><p><strong>Verdict:</strong> Static is an Architectural Dead End</p><p><strong>Reasoning:</strong><br> You cannot wait 5 minutes for a rollout when mitigating a DDoS attack via rate limiter adjustments. Constant restarts prevent the cluster from ever reaching a stable, JIT-optimized state.</p><h3><strong>The Solution: Standard vs. Custom</strong></h3><h4>Option A: Standard Spring Cloud Bus</h4><p>The classic enterprise pattern: <strong>Git → Config Server → Bus (RabbitMQ/Kafka) → Gateway</strong>.</p><p>The Hidden Bottleneck: ContextRefresher</p><p>The flaw lies in how Spring handles the RefreshRemoteApplicationEvent. It triggers a ContextRefresher, which effectively performs a “soft restart”:</p><ol><li><strong>Bean Destruction:</strong> All beans annotated with @RefreshScope are destroyed and recreated.</li><li><strong>Major GC Risk:</strong> This churn creates a massive wave of temporary objects, potentially triggering a generic “Stop-the-world” pause in high-memory heaps.</li><li><strong>CPU Spike:</strong> Proxy objects must be re-initialized.</li></ol><p><strong>Result:</strong> A noticeable lag and latency jitter (p99 degradation) every time a webhook triggers an update.</p><h4>Option B: The Lightweight Redis Approach (Proposed)</h4><p>Spring Cloud Gateway’s architecture separates route definition from route storage. By implementing the RouteDefinitionRepository interface, we can swap the default in-memory storage for a persistent, shared fast-access store.</p><p><strong>Architecture:</strong></p><ol><li><strong>Storage:</strong> Routes are stored as JSON in Redis.</li><li><strong>Signaling:</strong> We utilize <strong>Redis Pub/Sub</strong> for real-time notifications.</li><li><strong>Action:</strong> Gateway pods subscribe to the topic. Upon receiving a signal, they reload routes from Redis and fire a RefreshRoutesEvent internally.</li></ol><p><strong>Key Advantage:</strong> This avoids the ContextRefresher entirely. We only invalidate the route cache, which is orders of magnitude faster and lighter than refreshing the Spring Context.</p><h3>Under the Hood: Implementation Details</h3><h4>Full Control via DTO</h4><p>We define a RouteDefinitionDTO to act as our control plane contract. This allows dynamic tuning of not just paths, but resilience patterns.</p><pre>public class RouteDefinitionDTO {<br>    @NotBlank<br>    private String id;<br><br>    @NotBlank<br>    private String uri; // Target Service<br><br>    private ResilienceConfig config; // RateLimits, Timeouts<br>    private LocalCacheConfig cacheConfig; // Toggle caching on/off dynamically<br><br>    @Data<br>    public static class ResilienceConfig {<br>        private Integer replenishRate;      // Redis Rate Limiter<br>        private Integer burstCapacity;<br>        private Integer maxConcurrentCalls; // Bulkhead isolation<br>    }<br>}</pre><h4>The Mapper Strategy</h4><p>The RouteDefinitionMapper converts the DTO into a native RouteDefinition, automatically applying filter factories based on the configuration.</p><pre>public RouteDefinition convertToRouteDefinition(RouteDefinitionDTO dto) {<br>    RouteDefinition route = new RouteDefinition();<br>    //... basic mapping...<br><br>    List&lt;FilterDefinition&gt; filters = new ArrayList&lt;&gt;();<br>    <br>    // Dynamically attach filters based on DTO flags<br>    if (dto.getConfig().getMaxConcurrentCalls()!= null) {<br>        filters.add(bulkheadDefinition(dto.getId(), dto.getConfig().getMaxConcurrentCalls()));<br>    }<br>    <br>    if (dto.getCacheConfig().isEnabled()) {<br>        filters.add(localCacheDefinition(dto.getCacheConfig()));<br>    }<br><br>    route.setFilters(filters);<br>    return route;<br>}</pre><h4>Redis Repository &amp; Pub/Sub</h4><p>We implement a custom repository to fetch data from Redis and a listener to trigger the update.</p><pre>public class RedisRouteDefinitionRepository implements RouteDefinitionRepository {<br>    private final ReactiveStringRedisTemplate redisTemplate;<br>    <br>    @Override<br>    public Flux&lt;RouteDefinition&gt; getRouteDefinitions() {<br>        return redisTemplate.opsForHash().values(ROUTES_KEY)<br>           .map(json -&gt; objectMapper.readValue(json, RouteDefinitionDTO.class))<br>           .map(mapper::convertToRouteDefinition);<br>    }<br>}</pre><p><strong>The Listener (The “Magic” Part):</strong> Instead of the heavy ContextRefresher, we use the lightweight RefreshRoutesEvent:</p><pre>@Component<br>public class RedisRouteRefreshListener implements MessageListener {<br>    <br>    private final ApplicationEventPublisher publisher;<br><br>    @Override<br>    public void onMessage(Message message, byte pattern) {<br>        // Trigger purely the route cache rebuild, NOT the whole context<br>        publisher.publishEvent(new RefreshRoutesEvent(this));<br>    }<br>}</pre><p>This ensures that changes to Rate Limiters, Circuit Breakers, or routing rules apply in milliseconds across the entire cluster without performance degradation.</p><h3>The Trade-off: Audit &amp; GitOps</h3><p>The standard Spring Cloud Bus shines in one area: <strong>Auditability</strong>.</p><ul><li><strong>Redis Risks:</strong> Redis is a key-value store, not a version control system. It lacks history, git blame, and rollback capabilities. A manual SET command by an admin can break the cluster with no audit trail.</li></ul><p><strong>Mitigation: Hybrid GitOps</strong> To bring Enterprise-grade reliability to this custom solution, we implement a <strong>Hybrid GitOps</strong> pipeline:</p><ol><li><strong>Source of Truth:</strong> Git (YAML/JSON definitions).</li><li><strong>Validation:</strong> CI Pipeline runs schema validation and logical checks.</li><li><strong>Delivery:</strong> The CI/CD pipeline pushes the validated JSON to Redis and fires the Pub/Sub event.</li></ol><p>This gives us the best of both worlds: the speed of Redis for the <strong>Data Plane</strong> and the safety of Git for the <strong>Control Plane</strong>.</p><h3>5. Decision Matrix</h3><p>When deciding on a route management strategy, consider these four key factors:</p><ul><li><strong>Low Update Frequency (&lt; 10/day):</strong> Stick with <strong>Static or Kubernetes Rolling Updates</strong>. When your routes don’t change often, simplicity is your best friend.</li><li><strong>Strict Compliance &amp; Audit Requirements:</strong> Go with <strong>Spring Cloud Bus</strong>. Its native integration with Git history provides a built-in audit trail that is invaluable for enterprise compliance.</li><li><strong>High Frequency &amp; Low Latency:</strong> Choose a <strong>Custom Redis Implementation</strong>. If you’re managing real-time traffic at scale, Redis is essential for maintaining performance under pressure.</li><li><strong>The “Expertise” Factor:</strong> Keep in mind that a custom Redis setup isn’t a “plug-and-play” solution. It requires your team to have a deep understanding of <strong>Project Reactor and Netty</strong> to handle the underlying reactive stack.</li></ul><h3>Conclusion</h3><p>The custom Redis-based routing strategy is not a replacement for standard patterns but an optimization for specific high-performance requirements. By decoupling configuration storage from the application lifecycle and utilizing event-driven updates, we achieve true <strong>Zero Downtime</strong> configuration changes, effectively separating the Control Plane from the Data Plane in Spring Cloud Gateway.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21bc2922ef3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>