<?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 Ankit Tiwari on Medium]]></title>
        <description><![CDATA[Stories by Ankit Tiwari on Medium]]></description>
        <link>https://medium.com/@ankit4unet?source=rss-ac2baeae61cb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IfaY_tnfdOu0cI77K0gs6A.jpeg</url>
            <title>Stories by Ankit Tiwari on Medium</title>
            <link>https://medium.com/@ankit4unet?source=rss-ac2baeae61cb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:00:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ankit4unet/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[How Rate Limiting Actually Works in Internal Architecture — Trade-offs and Bottlenecks Nobody Warns…]]></title>
            <link>https://medium.com/@ankit4unet/how-rate-limiting-actually-works-in-internal-architecture-trade-offs-and-bottlenecks-nobody-warns-53e9f0302790?source=rss-ac2baeae61cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/53e9f0302790</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ankit Tiwari]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 18:43:11 GMT</pubDate>
            <atom:updated>2026-07-19T18:43:11.410Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Rate Limiting Actually Works in Internal Architecture — Trade-offs and Bottlenecks Nobody Warns You About</h3><p>Rate limiting sounds simple until you have to build one that survives real production traffic across hundreds of internal services. Every algorithm you pick trades away something — accuracy, latency, memory, or simplicity — and every distributed design introduces a new bottleneck at exactly the point you didn’t expect.</p><p>Here’s how it actually works underneath, where it breaks, and what to give up on purpose.</p><h3>Where Rate Limiting Lives in the Architecture</h3><p>Rate limiting can sit in four places, and the choice changes everything downstream:</p><ul><li><strong>Client-side</strong> — cheapest, but unenforceable. A misbehaving or compromised client ignores it entirely.</li><li><strong>API Gateway / Edge</strong> — the most common placement. One choke point, one policy, protects everything behind it.</li><li><strong>Service-level</strong> — each service enforces its own limit, useful when different services need different rules, but it multiplies the number of places state has to be tracked and synchronized.</li><li><strong>Downstream / database-level</strong> — the last line of defense, usually connection pooling or query throttling rather than true rate limiting.</li></ul><p>Most internal architectures land on gateway-level limiting for cross-cutting protection, plus service-level limiting for anything with a tighter SLA than the rest of the platform — payment endpoints, auth endpoints, anything that talks to a fragile downstream dependency.</p><h3>The Algorithms — and What Each One Actually Costs You</h3><p><strong>Fixed Window Counter</strong> Count requests in a time bucket (e.g., 100 requests per minute), reset the counter every minute. Cheapest to implement and reason about. The catch: a client can burst up to 2× the limit right at the window boundary — 100 requests in the last second of one window, another 100 in the first second of the next, and your “100/minute” limit just allowed 200 requests in two seconds.</p><p><strong>Sliding Window Log</strong> Store a timestamp for every request and count how many fall inside the trailing window. Accurate — no boundary burst problem — but memory cost scales linearly with request volume, which becomes a real problem at high throughput.</p><p><strong>Sliding Window Counter</strong> A weighted average between the current and previous fixed windows. Fixes most of the boundary-burst issue at a fraction of the memory cost of a full log. This is the practical middle ground most gateways actually use.</p><p><strong>Token Bucket</strong> Tokens refill at a fixed rate into a bucket with a max capacity; each request consumes a token. Allows controlled bursts up to bucket capacity, then throttles to the refill rate. This is usually the right choice when you want to allow short bursts (a user clicking rapidly) without allowing sustained abuse.</p><p><strong>Leaky Bucket</strong> Requests queue and drain at a fixed rate, smoothing bursts into a constant output rate. Good for protecting a downstream system that genuinely cannot handle bursts at all — but it adds latency, since excess requests wait in the queue instead of failing fast.</p><p>The trade-off in one line: <strong>fixed window is cheap and wrong at the edges, sliding window is accurate and costs memory, token bucket is the best default for user-facing APIs, leaky bucket is the right call when the downstream system, not the caller, is the fragile part.</strong></p><h3>The Distributed Systems Problem Nobody Mentions First</h3><p>A rate limiter on one machine is easy. The moment you have multiple gateway instances behind a load balancer, “100 requests per minute per user” requires <strong>shared state</strong> — and that’s where the real engineering starts.</p><p><strong>Option 1: Centralized store (Redis)</strong> Every instance checks and increments a counter in Redis using an atomic operation (INCR + EXPIRE, or a Lua script for token bucket logic). Accurate, consistent, but now Redis is in the hot path of every single request. Redis latency becomes your rate-limiter latency, and Redis availability becomes your gateway&#39;s availability — a Redis blip now degrades every request, not just the ones being throttled.</p><p><strong>Option 2: Local counters with periodic sync</strong> Each instance tracks its own count and syncs with a shared store every few hundred milliseconds. Removes Redis from the request’s critical path, but introduces a window where the <em>actual</em> traffic across all instances briefly exceeds the intended limit — because each instance is enforcing an approximation, not the true global count.</p><p><strong>Option 3: Sharded limits</strong> Split the global limit across instances (e.g., 10 instances → each enforces 1/10th of the limit locally). Fast and simple, but wastes capacity — an uneven traffic distribution across instances means some shards throttle early while others have unused headroom.</p><p>The honest trade-off: <strong>you can have strict accuracy, or you can have low latency and high availability — a distributed rate limiter under real load rarely gets to have both at the same time.</strong> Most production systems knowingly choose approximate enforcement (local counters or sharding) because a rate limiter that takes the whole gateway down when it’s slow is worse than one that’s occasionally 5% too generous.</p><h3>Where the Bottlenecks Actually Show Up</h3><p><strong>1. The rate-limiter store becomes the new single point of failure.</strong> Ironically, a system built to protect other services from overload can itself become the overloaded dependency. If every request round-trips to Redis before even reaching business logic, Redis’s p99 latency is now baked into every request’s p99 latency — including requests that were never going to be throttled.</p><p><strong>2. Hot keys.</strong> If rate limiting is keyed by user ID or API key, one extremely active key (a popular account, a misconfigured internal service hammering an endpoint) creates massive contention on a single counter, degrading performance for that key specifically even while the rest of the system is healthy.</p><p><strong>3. Clock skew across instances.</strong> Window-based algorithms depend on synchronized time. In distributed systems with even small clock drift, window boundaries don’t line up cleanly across instances, quietly reintroducing the boundary-burst problem sliding windows were supposed to fix.</p><p><strong>4. Cascading throttling.</strong> If a rate-limited response triggers an automatic client retry, and every client retries roughly around the same backoff interval, you get a synchronized retry storm hitting the same window boundary — which is the exact traffic spike the rate limiter was trying to prevent in the first place. This is why retry-after headers with jitter matter more than the rate-limiting algorithm itself.</p><h3>What This Looks Like in an IAM / API Gateway Context</h3><p>In a gateway sitting in front of hundreds of internal services, the practical shape usually ends up being layered rather than a single algorithm:</p><ul><li><strong>Coarse global limit</strong> at the edge (protects the gateway itself from being overwhelmed)</li><li><strong>Per-client token bucket</strong> (protects fairness between consumers, allows legitimate bursts)</li><li><strong>Per-downstream-service leaky bucket or circuit breaker</strong> (protects fragile dependencies that can’t absorb bursts, regardless of who’s calling them)</li></ul><p>None of these is “the” rate limiter — they’re three different problems wearing the same name, and conflating them is usually where designs go wrong. A limit protecting <em>fairness between callers</em> and a limit protecting <em>a downstream system’s survival</em> have different tolerances for burst, different acceptable latency costs, and often shouldn’t even use the same algorithm.</p><h3>The Trade-off, Stated Plainly</h3><p>Rate limiting is not a solved problem you implement once — it’s a set of three-way trade-offs (accuracy, latency, availability) you re-negotiate for every layer of the system. The right question isn’t “which algorithm is best,” it’s “what is this specific limit protecting, and what am I willing to sacrifice to protect it under real load.”</p><p><em>If this was useful, follow for more breakdowns of how production platform architecture actually holds up under scale.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53e9f0302790" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[20 Spring Architect Interview Questions]]></title>
            <link>https://medium.com/@ankit4unet/20-spring-architect-interview-questions-829b0d5d92e7?source=rss-ac2baeae61cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/829b0d5d92e7</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-ioc]]></category>
            <dc:creator><![CDATA[Ankit Tiwari]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 18:38:43 GMT</pubDate>
            <atom:updated>2026-07-19T18:38:43.286Z</atom:updated>
            <content:encoded><![CDATA[<p>Most “Spring Architect interview questions” lists online give you Wikipedia-style definitions. That’s not how architect interviews actually go — you get thrown a broken production scenario and asked to think out loud: investigate, fix, prove it worked.</p><p>Here are 20 real scenario-based questions with the kind of answers that hold up in an actual interview.</p><p><strong>Q1. A production system using IoC Container starts failing intermittently under peak traffic. How would you investigate and redesign it?</strong></p><blockquote>It’s rarely the container itself — check for singleton beans holding mutable state (thread-unsafe under concurrency), prototype-scoped beans being created excessively (GC pressure), or circular dependencies triggering lazy-init races under load. Investigate with heap dumps and thread dumps captured during a failure window, review bean creation logs, and check connection pool exhaustion — a bean wrapping a pooled resource is a common culprit. Redesign by moving mutable state out of singletons, scoping beans correctly, and adding circuit breakers around beans that wrap external calls.</blockquote><p><strong>Q2. Traffic grows 10× and the current IoC container design becomes the bottleneck. What would you change first?</strong></p><blockquote>First, verify it’s actually the container and not what the beans *do* — profile bean initialization time and check for lazy-init heavy beans loading under request pressure. Warm up the application context ahead of traffic instead of cold-starting under load. If genuinely container-related (rare, since beans are typically created once), cache expensive bean graphs and avoid prototype scope on hot paths. In practice, redirect the investigation toward downstream dependencies like DB connection pools and thread pool sizing — “the IoC container is the bottleneck” is an uncommon root cause, and a strong candidate says so.</blockquote><p>— -</p><p><strong>Q3. A dependency outage causes a feature built around IoC Container to cascade across the application. How do you contain it?</strong></p><blockquote><em>Wrap the bean that calls the dependency in a circuit breaker (Resilience4j), add fallback methods, and use bulkheading — separate thread pools per dependency so one outage doesn’t starve everything else. Structurally, avoid letting a single service bean own calls to multiple downstream systems; isolate per-dependency clients so failure blast radius stays scoped to one bean instead of the whole feature.</em></blockquote><p>— -</p><p><strong>Q4. Two concurrent requests interact with the IoC container and produce inconsistent results. How would you make the flow correct?</strong></p><blockquote>This is a scope/state bug, not a container bug — almost always a singleton bean holding per-request mutable fields. Fix it by making the bean stateless, passing state through method parameters, or using ThreadLocal carefully (with explicit cleanup) if per-thread state is unavoidable. Validate with a load test that hits the same bean concurrently and asserts response isolation.</blockquote><p><strong>Q5. How would you prove that your redesign actually solved the production problem?</strong></p><blockquote>Compare before/after metrics under the same load profile: error rate, p99 latency, GC pause frequency, and thread pool queue depth. Reproduce the original failure condition in staging first through a chaos test, confirm it fails, apply the fix, then confirm it doesn’t fail anymore. A fix without a reproducible failing test beforehand isn’t proven — that’s the standard an architect should hold themselves to.</blockquote><p>— -</p><p><strong>Q6. A production system using Spring Boot Auto-Configuration starts failing intermittently. How would you investigate it?</strong></p><blockquote>Enable debug conditionally or check the ConditionEvaluationReport to see which auto-configurations activated. Intermittent failures are usually caused by a race in conditional bean creation order, or an auto-configured bean (like a default DataSource pool) silently overriding a custom one depending on startup timing. Check for multiple candidate beans matching a conditional with non-deterministic selection.</blockquote><p>— -</p><p><strong>Q7. Traffic increases 10× and auto-configuration becomes a bottleneck. What would you optimize first?</strong></p><blockquote>Auto-configuration itself only runs at startup, so “bottleneck” usually means an auto-configured default — connection pool size, thread pool size, buffer size — that was fine at normal load but starves at 10×. The first move is auditing every auto-configured default (HikariCP pool size, Tomcat thread count, Jackson buffer sizes) and explicitly tuning them instead of trusting Spring Boot’s defaults.</blockquote><p>— -</p><p><strong>Q8. How do you isolate failures caused by misconfigured auto-configuration?</strong></p><blockquote>Use `<a href="http://twitter.com/ConditionalOnPropert">@ConditionalOnPropert</a>y` gating for anything sensitive, mark intended beans with `<a href="http://twitter.com/Primary">@Primary</a>` explicitly, and exclude unused auto-configurations to shrink the surface area. The `actuator/conditions` endpoint shows live evaluation on a running instance, which is far more useful than only reading startup logs.</blockquote><p>— -</p><p><strong>Q9. How do you handle concurrency issues introduced by auto-configuration?</strong></p><blockquote>Same root cause as singleton state bugs — auto-configured beans are singletons by default. If an auto-configured bean like an ObjectMapper or RestTemplate is being mutated per request somewhere in application code, that’s the actual bug. The fix belongs at the usage site, not in Spring’s configuration.</blockquote><p>— -</p><p><strong>Q10. How would you validate your solution before deploying to production?</strong></p><blockquote>Run contract tests and integration tests against a prod-like profile, canary deploy to a small percentage of live traffic, and have a rollback plan tested in advance rather than improvised during an incident. Feature-flag the change if it touches a hot path.</blockquote><p>— -</p><p><strong>Q11. How would you design authentication for millions of users using Spring Security?</strong></p><blockquote>Stateless JWT-based authentication with a short-lived access token and a refresh token, OAuth2/OIDC via an external identity provider like Keycloak for federation, and token validation cached at the gateway layer so requests aren’t hitting the identity provider on every call. Auth-check logic scales horizontally since there’s no server-side session to pin. Rate-limit authentication endpoints separately — they’re the most attacked surface in the system.</blockquote><p>— -</p><p><strong>Q12. How do you prevent cascading failures across Spring Cloud microservices?</strong></p><blockquote>Circuit breakers and bulkheads on every downstream call, timeouts everywhere — a call with no timeout is a future outage — and retry with backoff instead of naive retry, which amplifies load during an incident. A service mesh or gateway-level rate limiting keeps one slow service from fanning backpressure out to everything calling it.</blockquote><p>— -</p><p><strong>Q13. How would you design an event-driven architecture using Kafka for high throughput?</strong></p><blockquote>Partition by a key that distributes load evenly while preserving necessary ordering, such as user ID. Size partition count to match or exceed expected consumer parallelism. Batch producer sends, and tune consumer settings like `max.poll.records` and `fetch.min.bytes` to balance throughput against latency. Enable idempotent producer configuration for exactly-once semantics.</blockquote><p>— -</p><p><strong>Q14. How do you guarantee message ordering and exactly-once processing?</strong></p><blockquote>Ordering is only guaranteed within a partition, so key messages so related events land on the same partition. For exactly-once processing, enable idempotent producer settings alongside transactional producer/consumer configuration with `read_committed` isolation, or deduplicate at the consumer using an idempotency key if full Kafka transactions are too heavy for the use case.</blockquote><p>— -</p><p><strong>Q15. When would you choose WebFlux over Spring MVC?</strong></p><blockquote>Choose WebFlux when the workload is I/O-bound with high concurrency and needs to scale without a thread-per-request model — a gateway or aggregation layer calling multiple downstream services is a good example. Choose Spring MVC when the team’s mental model, libraries (like blocking JDBC), and debugging tooling are simpler, and traffic doesn’t demand reactive’s added complexity. Most CRUD services don’t need WebFlux, and adopting it without a genuine I/O-bound justification just adds complexity for no benefit.</blockquote><p>— -</p><p><strong>Q16. How do you optimize Hibernate performance under heavy load?</strong></p><blockquote>Eliminate N+1 queries using fetch joins or entity graphs, batch inserts and updates through the JDBC batch size setting, add a second-level cache for read-heavy reference data, avoid open-session-in-view in high-throughput services since it holds connections longer than necessary, and paginate instead of loading full collections into memory.</blockquote><p>— -</p><p><strong>Q17. How do you troubleshoot deadlocks caused by Spring transactions?</strong></p><blockquote>Start with the database-level deadlock graph — most databases log it — and correlate it with transactional method boundaries. Deadlocks almost always come from two transactions acquiring row locks in different orders. Fix it with consistent lock ordering across code paths, shorter transaction boundaries (avoid slow I/O inside a transactional method), and consider a less strict isolation level if the default is over-isolating unnecessarily.</blockquote><p>— -</p><p><strong>Q18. How do you design resilient distributed transactions using the Saga pattern?</strong></p><blockquote>Use choreography — each service publishes events and others react — for simpler flows with few steps. Use orchestration, with a central saga coordinator, when the flow needs more visibility and easier compensation-logic management at scale. Every step needs a compensating action, and handlers must be idempotent since saga steps can be retried. Track saga state explicitly, such as in a saga log or table, so the flow can recover from a coordinator crash mid-transaction.</blockquote><p>— -</p><p><strong>Q19. How do you design a highly available Spring Boot architecture?</strong></p><blockquote>Stateless services behind a load balancer, externalized session and state storage (like Redis), multi-availability-zone deployment, health checks feeding into the load balancer or orchestrator so unhealthy instances get pulled automatically, circuit breakers on all downstream calls, and a tested failover path for the datastore layer using read replicas with automated promotion.</blockquote><p>— -</p><p><strong>Q20. What trade-offs would you make as an Architect when performance, consistency, and scalability conflict?</strong></p><blockquote>This is the question that separates architects from engineers. My approach: default to eventual consistency at the edges of the system, where staleness is tolerable to the business, and strong consistency at the core of the domain — money, entitlements, anything where being wrong is worse than being slow. State explicitly which parts of the system were made consistent versus available, and why. Picking one consistency model and applying it everywhere is an engineer’s answer; explaining the boundary and the reasoning behind it is an architect’s answer.</blockquote><p><em>If you found this useful, follow for more real-world architecture interview breakdowns.</em></p><p>*If you found this useful, follow for more real-world architecture interview breakdowns.*</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=829b0d5d92e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Practices for Logging and Log Aggregation in Spring Microservices Architecture]]></title>
            <link>https://medium.com/@ankit4unet/best-practices-for-logging-and-log-aggregation-in-spring-microservices-architecture-9299d5c1b133?source=rss-ac2baeae61cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/9299d5c1b133</guid>
            <category><![CDATA[microservices-application]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[logging-and-monitoring]]></category>
            <dc:creator><![CDATA[Ankit Tiwari]]></dc:creator>
            <pubDate>Fri, 03 Nov 2023 06:53:56 GMT</pubDate>
            <atom:updated>2023-11-03T06:53:56.380Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding Asynchronous Programming in Rust: Simplifying Complexity for Improved Performance and Safety. Discover Essential Design Patterns and Benefits for Effective Asynchronous Coding. Whether you’re new to Rust’s async features or need a quick review, this guide offers clear insights and practical advice. Let’s get started!</p><p>Microservices have revolutionized the way we build and deploy applications, enabling us to create complex systems that are more scalable, flexible, and maintainable. However, as the number of microservices grows, ensuring effective logging and log aggregation becomes increasingly critical. In this article, we will delve into the best practices for implementing logging and log aggregation in Spring microservices architecture, providing insights to help you streamline your development process and ensure the smooth operation of your distributed system.</p><p>Logging Best Practices in Spring Microservices:</p><ol><li>Utilize a logging framework: Choose a logging framework that aligns with your requirements and the specific needs of your microservices. Leverage Spring Boot’s support for popular logging frameworks such as Logback, Log4j2, or java.util.logging.</li><li>Implement structured logging: Adopt structured logging techniques, such as formatting logs in JSON using libraries like Logback JSON or Log4j2 JSONLayout. Structured logging simplifies log analysis and aggregation, providing a clearer understanding of system behavior.</li><li>Define appropriate logging levels: Employ different logging levels, including DEBUG, INFO, WARN, and ERROR, based on the severity and significance of the logged events. This ensures that the appropriate level of detail is captured for effective monitoring and troubleshooting.</li><li>Include contextual information: Enhance the context of your logs by incorporating relevant details such as request and session IDs, timestamps, user IDs, and other pertinent metadata. This contextual information is instrumental in understanding the flow of requests and identifying the source of potential issues.</li></ol><p>Log Aggregation Best Practices in Spring Microservices Architecture:</p><ol><li>Set up a centralized log management system: Implement a robust log aggregation solution to collect, store, and analyze logs from multiple microservices. Consider using popular tools like the ELK stack (Elasticsearch, Logstash, Kibana), Splunk, or Sumo Logic to centralize log data for efficient monitoring and analysis.</li><li>Enable distributed tracing: Employ distributed tracing tools like Spring Cloud Sleuth or OpenTelemetry to trace requests across various microservices. Distributed tracing aids in identifying performance bottlenecks and ensuring seamless communication between microservices.</li><li>Real-time log monitoring: Configure real-time log monitoring using monitoring tools like Prometheus, Grafana, or Kibana. Create custom dashboards and set up alerts to promptly respond to critical events and monitor the overall health and performance of your microservices.</li><li>Secure sensitive information: Safeguard sensitive data by implementing techniques such as log masking or encryption to prevent unauthorized access or exposure of critical information in logs.</li></ol><p>Conclusion: Implementing effective logging and log aggregation practices is essential for maintaining the performance, security, and reliability of your Spring microservices architecture. By adhering to these best practices, you can ensure seamless monitoring, efficient troubleshooting, and enhanced overall system performance, enabling your microservices to operate smoothly within a distributed environment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9299d5c1b133" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>