<?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 Mayuresh Gadre on Medium]]></title>
        <description><![CDATA[Stories by Mayuresh Gadre on Medium]]></description>
        <link>https://medium.com/@mayureshgadre244?source=rss-6814632c5b18------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*tthU-LZ6ZktKYp22</url>
            <title>Stories by Mayuresh Gadre on Medium</title>
            <link>https://medium.com/@mayureshgadre244?source=rss-6814632c5b18------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:49:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mayureshgadre244/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[Testing SAML Based SSO Configurations with Keycloak]]></title>
            <link>https://medium.com/@mayureshgadre244/testing-saml-based-sso-configurations-with-keycloak-006b15b741a9?source=rss-6814632c5b18------2</link>
            <guid isPermaLink="false">https://medium.com/p/006b15b741a9</guid>
            <category><![CDATA[single-sign-on]]></category>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[saml2]]></category>
            <dc:creator><![CDATA[Mayuresh Gadre]]></dc:creator>
            <pubDate>Sun, 06 Oct 2024 17:46:40 GMT</pubDate>
            <atom:updated>2024-10-11T08:27:22.795Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*3G2ok7ky1J3JX1kf_jKAjA.jpeg" /></figure><p><strong>Single Sign-On (SSO)</strong> is an essential feature in many modern applications, providing a seamless and secure user experience. However, configuring SSO correctly can be challenging, especially when integrating with multiple Identity Providers (IDPs). Common issues such as misconfigured SAML attributes or incorrect URL mappings can cause login failures, leaving users frustrated and IT teams scrambling for solutions.</p><p>To address these challenges, I built a tool that simplifies the <strong>SSO configuration</strong> process. In this article, I’ll guide you through a custom-built tool that simplifies the process of testing SSO connections when configuring IDPs in Keycloak, allowing you to verify configurations and diagnose issues quickly.</p><h3>Common Challenges in SSO Configuration</h3><p>Configuring SSO with an IDP typically requires knowledge of SAML, URL endpoints, certificates, and user attributes. Some common challenges include:</p><ul><li><strong>Incorrect IDP settings</strong>: Wrong ACS URL, certificates, or entity IDs.</li><li><strong>SAML response issues</strong>: The SAML response may not contain the expected attributes or may have validation issues.</li><li><strong>Troubleshooting failures</strong>: Debugging why an SSO login attempt fails often involves reviewing logs or raw SAML data, which can be overwhelming.</li></ul><h3>Self-Serve SSO Configuration</h3><p>Wouldn’t it be easier if users could test their SSO connection before committing the settings? The tool is designed to empower users to configure SSO on their own without needing extensive technical support.</p><h3>How the Tool Works</h3><p>The tool is structured into two main components: a UI application that handles user interaction and configuration, and a Keycloak extension on the backend that manages SAML response validation and provides real-time feedback.</p><p><strong>Step 1: Configuring the SSO Settings</strong></p><p>This tool features a SSO settings page where users can enter the configuration details for their chosen Identity Provider (IDP), such as the Entity ID, SSO URL, and certificates. These configuration parameters are typically supplied by the IDP.</p><p><strong>Step 2: Test Connection</strong></p><p>Before the users save the IDP configuration, they must first test the connection. Clicking the “Test Connection” button will initiate a redirection process, sending the user to the IDP for login. the SSO URL is dynamically retrieved from the configuration provided by the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NJeQurugk4Hn-M_llQ9QpA.jpeg" /></figure><p><strong>Step 3: IDP Redirection and Login</strong></p><p>Once redirected to the IDP, the user enters their credentials. Upon successful authentication, the IDP sends a SAML response back to Keycloak’s Assertion Consumer Service (ACS) URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VREGpZrv7Cypv02wWCPxvA.png" /></figure><p><strong>Step 4: Intercepting the SAML Response</strong></p><p>At this point, custom-built Keycloak extension intercepts the SAML response. This extension is crucial as it parses the response and checks for any errors. For example, it validates signatures, checks expiration timestamps, and ensures that attributes match the expected configuration.</p><p><strong>Step 5: Displaying the Result</strong></p><p>After validating the SAML response, the tool provides immediate feedback:</p><ul><li><strong>Success:</strong> If everything checks out, a success message is shown, confirming that the IDP configuration is correct.</li><li><strong>Failed:</strong> If there’s an issue, the tool provides detailed error messages, helping users diagnose the problem. For instance, it could be a mismatched audience, an expired assertion, or an invalid signature.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*ICxFW_h3ioU-K52on8wWnA.jpeg" /></figure><h3>Common Issues and How the Tool Helps</h3><ol><li><strong>Incorrect ACS URLs</strong><br>The tool ensures that the user-supplied IDP URLs are correctly formatted and reachable.</li><li><strong>Signature Validation Errors</strong><br>If the SAML response signature is invalid, the tool will notify the user to check the certificates.</li><li><strong>Other Errors </strong><br>The tool checks for any other errors like NameID mismatch, Login timeout error or invalid audience error etc.</li></ol><h3>Technical Implementation</h3><p>To build this tool, I created a Keycloak extension by extending org.keycloak.broker.saml.SAMLIdentityProvider. This allowed me to override methods for deeper control over how Keycloak handles SAML requests and responses, enabling us to intercept, validate, and provide real-time feedback to users during the SSO test process.</p><p><strong>Differentiating Test vs. Actual Login Requests</strong></p><p>To distinguish between an actual login request and a test connection request, a specific string is passed in the <strong>RelayState</strong>. This ensures that the tool knows when it’s handling a test connection, allowing it to manage the flow accordingly without affecting real login attempts.</p><p><strong>Overriding </strong><strong>SAMLIdentityProvider</strong></p><p>The SAMLIdentityProvider class handles the interaction between Keycloak and external SAML Identity Providers. By overriding this class, we can customize the authentication flow for different IDP configurations, ensuring compatibility with various SAML-based identity systems</p><pre>@AutoService(IdentityProviderFactory.class)<br>public class TestSamlIdentityProviderFactory extends SAMLIdentityProviderFactory {<br><br>    public static final String PROVIDER_ID = &quot;saml&quot;;<br>    private DestinationValidator destinationValidator;<br><br>    @Override<br>    public String getName() {<br>        return &quot;Test SAML v2.0&quot;;<br>    }<br><br>    @Override<br>    public TestSamlIdentityProvider create(KeycloakSession session, IdentityProviderModel model) {<br>        return new TestSamlIdentityProvider(session, new SAMLIdentityProviderConfig(model), destinationValidator);<br>    }<br><br>    @Override<br>    public String getId() {<br>        return PROVIDER_ID;<br>    }<br><br>    @Override<br>    public void init(Config.Scope config) {<br>        super.init(config);<br><br>        this.destinationValidator = DestinationValidator.forProtocolMap(config.getArray(&quot;knownProtocols&quot;));<br>    }<br>}</pre><pre>public class TestSamlIdentityProvider extends SAMLIdentityProvider {<br><br>    protected static final Logger logger = Logger.getLogger(TestSamlIdentityProvider.class);<br><br>    private final DestinationValidator destinationValidator;<br>    private final KeycloakSession session;<br><br>    public TestSamlIdentityProvider(KeycloakSession session, SAMLIdentityProviderConfig config, DestinationValidator destinationValidator) {<br><br>        super(session, config, destinationValidator);<br>        this.destinationValidator = destinationValidator;<br>        this.session = session;<br>    }<br><br>    @Override<br>    public Object callback(RealmModel realm, IdentityProvider.AuthenticationCallback callback, EventBuilder event) {<br>        return new TestSamlEndpoint(realm, this, getConfig(), callback, destinationValidator, session);<br>    }<br><br>    @Override<br>    public Response performLogin(AuthenticationRequest request) {<br>        // add your code here<br>    }<br>}<br>  </pre><p><strong>Overriding </strong><strong>SAMLEndpoint</strong></p><p>The SAMLEndpoint class is responsible for processing SAML requests and responses. We gain control over two critical methods:</p><ul><li><strong>handleSamlRequest</strong>: Processes the authentication request from the IDP based on user-provided configurations.</li><li><strong>handleSamlResponse</strong>: Intercepts and validates the SAML response, ensuring elements such as signatures, assertion details, and required attributes are correct.</li></ul><h3>Conclusion</h3><p>SSO configuration can be challenging, especially when dealing with multiple IDPs. With this tool, testing and validating these configurations is much easier, saving time and reducing frustration. If you’re working with Keycloak and SAML-based SSO, this tool can significantly streamline your workflow and empower users to self-serve their SSO configurations effectively.</p><p>It’s important to mention that this tool specifically verifies SP-initiated logins. This means it tests the flow where the user initiates authentication from the the Keycloak client applications rather than from IDP.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=006b15b741a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving Kafka Consumer Crashes: A Practical Approach to Tuning Configuration Settings]]></title>
            <link>https://medium.com/@mayureshgadre244/solving-kafka-consumer-crashes-a-practical-approach-to-tuning-configuration-settings-8a5e29684af4?source=rss-6814632c5b18------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a5e29684af4</guid>
            <category><![CDATA[kafka-consumer]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Mayuresh Gadre]]></dc:creator>
            <pubDate>Sun, 06 Oct 2024 10:57:40 GMT</pubDate>
            <atom:updated>2024-10-06T10:57:40.701Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AeB7HVVzdVm6okogvTAQww.jpeg" /></figure><p>In distributed systems, Kafka is widely known for its scalability and fault tolerance when dealing with high-throughput data streams. However, even the most robust systems can encounter unexpected challenges that require deep understanding and precise configuration tweaks. In this article, I’ll share a Kafka consumer issue we faced at work — a situation where the consumer kept crashing, leading to repeated processing of the same event and an event backlog that grew to 80,000. I’ll explain how we identified the problem and the steps we took to resolve it by fine-tuning Kafka consumer configuration.</p><h4><strong>The Problem: Kafka Consumer Crash and Event Reprocessing</strong></h4><p>Kafka’s consumers are at the heart of any event-driven architecture, responsible for retrieving messages from Kafka topics and processing them. In our case, we had a typical Kafka consumer setup that had been working fine, but one day we started noticing something unusual — our consumer was repeatedly crashing, and each time it restarted, it processed the same event again and again.</p><p>Initially, we thought it might be a temporary network issue, but as we dug deeper, it became clear that something else was happening. The event lag continued to grow exponentially, and before we knew it, there were 80,000 unprocessed events in the queue.</p><h4>Symptoms We Observed:</h4><ul><li><strong>Consumer kept crashing</strong>: The consumer was failing to stay connected to the Kafka broker for an extended period.</li><li><strong>Repeated event processing</strong>: The same events were processed repeatedly, indicating that the offsets were not being committed correctly.</li><li><strong>Event backlog</strong>: The lag (difference between the last processed message and the latest message in the topic) grew to over 80,000 events.</li></ul><p>The severity of the situation grew as our system started to fall behind in processing real-time events, affecting downstream services that relied on timely data. We knew we had to find the root cause quickly.</p><h3>Diagnosing the Issue: Uncommitted Offsets</h3><p>After carefully reviewing the logs and the consumer configuration, we discovered that the Kafka consumer was not committing the offsets correctly. In Kafka, a consumer maintains an offset, which tracks the position of the next record to read from a partition. If the offset is not committed, the consumer will keep processing the same messages upon restart, leading to duplication.</p><p>But why was this happening?</p><p>The Kafka consumer was frequently crashing, and since the offsets were not being committed before the crash, the same event was processed again when the consumer came back online. This continuous cycle caused a growing backlog of unprocessed events and a frustratingly high lag.</p><h3>The Solution: Fine-Tuning Kafka Consumer Configuration</h3><p>To fix the problem, we needed to focus on why the consumer was crashing in the first place. We quickly realized that the default consumer configurations were not optimal for our use case. Kafka provides several consumer settings that allow fine control over how consumers interact with brokers. Tweaking these settings was the key to solving the issue.</p><p>Here’s what we did:</p><h3>1. session.timeout.ms: 60 seconds</h3><p>The session.timeout.ms property controls how long a consumer can go without sending a heartbeat to the Kafka broker before it is considered dead and removed from the consumer group, which in turn triggers a re-balancing event. By default, this timeout is set to a lower value, typically 10 seconds, which works well for systems where processing each event takes a short time. However, in our case, each event required significant processing—due to factors like complex transformations, database lookups, or integration with external services.</p><p>Given the intensive nature of event processing, the consumer was unable to send heartbeats in time, leading to it being considered dead, which caused Kafka to repeatedly remove the consumer and trigger re-balancing. To solve this, we increased the session.timeout.ms to 60<strong> seconds</strong>, allowing the consumer to stay in the group longer without being marked as dead, even if processing a single event took some time. This change provided the consumer ample time to finish processing without Kafka initiating unnecessary re-balancing.</p><pre>session.timeout.ms: 60000 # 60 seconds</pre><h3>2. heartbeat.interval.ms: 20 seconds</h3><p>The heartbeat.interval.ms property controls how frequently the consumer sends heartbeats to the Kafka broker to indicate that it is alive and active within the consumer group. Setting this value correctly is crucial to maintain the consumer&#39;s presence in the group.</p><p>For our configuration, we set heartbeat.interval.ms to <strong>20 seconds</strong>. This allows the consumer to send heartbeats regularly enough to ensure it is still considered alive by the broker, while not overwhelming the network with too frequent heartbeats. By keeping it lower than session.timeout.ms, we ensure that the consumer can send several heartbeats during the session timeout period, effectively keeping it alive even during longer processing times.</p><h3>3. max.poll.interval.ms: 40 seconds</h3><p>The max.poll.interval.ms property determines the maximum time allowed between calls to the consumer&#39;s poll() method. If the interval between poll() calls exceeds this timeout, the consumer is considered to have failed and is removed from the group, leading to rebalancing.</p><p>In our case, the consumer was taking longer to process batches of records, and as a result, it was failing to call poll() within the default interval. This timeout caused the broker to assume the consumer had failed and kicked it out of the group.</p><p>We adjusted this setting to 4<strong>0 seconds</strong> to give the consumer enough time to process records before being considered failed.</p><pre>max.poll.interval.ms: 40000 # 40 seconds</pre><h3>4. max.poll.records: 1</h3><p>Finally, we tuned the max.poll.records property. This setting controls the maximum number of records returned in a single call to poll(). Our consumer was fetching a large batch of records but struggling to process them quickly enough, leading to the re-balancing issues mentioned earlier.</p><p>To alleviate this, we reduced the value to <strong>1</strong>, meaning the consumer would fetch and process only one record at a time. This change significantly reduced the processing time per poll, improving overall stability. This ensured that each event could be processed within the constraints set by the timeout intervals above, preventing the consumer from being overwhelmed by large batches of records and ensuring stable, consistent performance.</p><pre>max.poll.records: 1</pre><h3>The Result: A Stabilized Kafka Consumer</h3><p>After applying these configuration changes, the consumer stopped crashing and started processing events normally. The growing event lag, which had peaked at 80,000, gradually decreased as the consumer worked through the backlog without reprocessing the same events.</p><p>These adjustments allowed the consumer to:</p><ul><li>Maintain a stable connection with the Kafka broker.</li><li>Process events efficiently without being removed from the consumer group.</li><li>Commit offsets correctly, ensuring that each event was processed only once.</li></ul><h3>Key Takeaways</h3><p>This experience highlighted the importance of tuning Kafka consumer configurations to suit specific workloads. While Kafka’s default settings may work for simple use cases, high-throughput environments or workloads with complex processing may require careful adjustment to avoid issues like consumer crashes and event lag.</p><p>Here are the key takeaways from our experience:</p><ol><li><strong>Understand Kafka’s consumer settings</strong>: Properties like session.timeout.ms, heartbeat.interval.ms , max.poll.interval.ms, and max.poll.records play crucial roles in consumer stability. Adjust them based on your system’s performance.</li><li><strong>Watch out for re-balancing</strong>: Frequent consumer group re-balancing can lead to instability and degraded performance. Optimising consumer settings can help prevent this.</li><li><strong>Test configurations in real-world scenarios</strong>: Don’t rely solely on default configurations. Simulate high-throughput scenarios to fine-tune settings for your use case.</li></ol><h3>Conclusion</h3><p>Kafka provides a powerful, scalable solution for event streaming, but its consumer configuration can be a double-edged sword if not tuned properly. By adjusting just four properties, we were able to solve our consumer crash issue, prevent event reprocessing, and process the backlog efficiently. If you’re facing similar issues with your Kafka consumer, consider reviewing your consumer configuration and making the necessary adjustments to keep your system stable and efficient.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a5e29684af4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>