<?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 Seetha Wenner on Medium]]></title>
        <description><![CDATA[Stories by Seetha Wenner on Medium]]></description>
        <link>https://medium.com/@seethawenner?source=rss-e88dd7601d3c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*m9VcNRfNizdP3oY9eqhnSQ.jpeg</url>
            <title>Stories by Seetha Wenner on Medium</title>
            <link>https://medium.com/@seethawenner?source=rss-e88dd7601d3c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 19:50:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@seethawenner/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[Redis Client Tracking using Redisson Client]]></title>
            <link>https://seethawenner.medium.com/redis-client-tracking-using-redisson-client-77a44349a58c?source=rss-e88dd7601d3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/77a44349a58c</guid>
            <category><![CDATA[client-side-caching]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[java-cache]]></category>
            <category><![CDATA[redisson]]></category>
            <dc:creator><![CDATA[Seetha Wenner]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 17:45:58 GMT</pubDate>
            <atom:updated>2025-10-07T17:45:58.369Z</atom:updated>
            <content:encoded><![CDATA[<p>Many applications cache data to answer requests within a few milliseconds. But what if you need sub-millisecond latency while processing billions of telemetry messages or financial transactions? You can “level-up” your cache by adding a client-side (a.k.a. “near”) cache.</p><p>This post explains Redis client-side caching concepts and demonstrates an implementation with the Redisson Java client library.</p><p><strong>What is client side caching or near cache?</strong><br>Client-side caching stores a subset of data directly in the application’s memory — for example, a Java Map in the JVM heap. The data can be read locally, eliminating even the network hop to Redis and enabling sub-millisecond latency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-JPQW-WH92hd0IT0jVqEHA.png" /></figure><p>Things to keep in mind when using a near cache<br>• Reduce the amount of data stored locally. Most clients do not need the entire dataset that lives in Redis.<br>• Always apply a TTL (time-to-live) or an eviction policy to free memory used by infrequently accessed keys.<br>• If your workload is write-heavy, near caching may hurt more than help because the server must send many invalidation messages to every client.<br>• Consider sharding data across application instances so that each JVM does not hold every key.</p><p><strong>How does Redis client tracking works?</strong></p><p>Below diagram shows an example of the protocol handshake between the server and clients. But the handshake might work different depending on the mode being used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*savlNXUDbqcifCe20xtT_Q.png" /></figure><ol><li>Connections start with tracking disabled.</li><li>When a client enables tracking, the server remembers which keys that client reads.</li><li>When another client writes, expires, or evicts one of those keys, Redis sends an invalidation message to every tracked client that may have cached the key.</li><li>Each client must delete the local copy to avoid serving stale data on the arrival of invalidation message.</li></ol><p><strong>Per-key Mode</strong></p><p>Every key that is mentioned in the context of a read-only command by all of its clients, is tracked by the server, because it <em>could be cached</em>.</p><p>The server remembers the list of clients that may have cached a given key in a single internal global table. This table is called the Invalidation Table.</p><p><strong>Broadcast Mode</strong></p><p>Every time a key matching any of the prefixes is modified, all the clients subscribed to that prefix, will receive the invalidation message.</p><p>The server stores data in Prefixes Table, where each prefix is associated to a list of clients.</p><p>More details <a href="https://redis.io/docs/latest/develop/use/client-side-caching/">here</a></p><p><strong>Redisson implementation example using RLocalCacheMap</strong></p><p>Will dive into the implementation details using <a href="https://github.com/redisson/redisson">Redisson Java client library.</a></p><p><a href="https://github.com/redisson/redisson/wiki/7.-Distributed-collections">Redisson support local cache for many data structures</a>.</p><p>local cache — so called near cache used to speed up read operations and avoid network roundtrips. It caches Map entries on Redisson side and executes read operations up to 45x faster in comparison with common implementation. Local cache instances with the same name connected to the same pub/sub channel. This channel is used for exchanging of update/invalidate events between all instances. Local cache store doesn&#39;t use hashCode()/equals() methods of key object, instead it uses hash of serialized state. It&#39;s recommended to use each local cached instance as a singleton per unique name since it has own state for local cache.</p><p>In this example we are using RLocalCacheMap which is available in the open-source version.</p><pre>@Configuration<br>public class CacheConfig {<br><br>    @Bean<br>    public RLocalCachedMap&lt;String, byte[]&gt; vehiclesLocalCache(<br>            RedissonClient redisson,<br>            VehicleBucketTrackingListener trackingListener) {<br><br>        LocalCachedMapOptions&lt;String, byte[]&gt; opts = LocalCachedMapOptions<br>                .&lt;String, byte[]&gt;defaults()<br>                .cacheSize(100_000) // Maximum size of the local cache<br>                .syncStrategy(SyncStrategy.INVALIDATE)<br>                .cacheProvider(CacheProvider.CAFFEINE)<br>                .timeToLive(Duration.ofDays(10))<br>                .maxIdle(Duration.ofDays(5))<br>                .storeMode(StoreMode.LOCALCACHE)<br>                .reconnectionStrategy(ReconnectionStrategy.LOAD);<br><br>        RLocalCachedMap&lt;String, byte[]&gt; map =<br>                redisson.getLocalCachedMap(&quot;vehiclesLocalCache&quot;, opts);<br><br>        map.addListener(trackingListener);<br>        return map;<br>    }<br>}</pre><p>The client tracking listener is invoked when an invalidation message is received if the data previously requested has been changed. Next listener invocation will be made, only if a new data request has been made and another change has occurred since then.</p><p>TrackingListener listens to created/removed/updated events after read operation.</p><pre>import org.redisson.api.listener.TrackingListener;<br>import org.redisson.api.RLocalCachedMap;<br><br>@Slf4j<br>@RequiredArgsConstructor<br>@Component<br>public class VehicleBucketTrackingListener implements TrackingListener {<br><br>    private final RLocalCachedMap&lt;String, byte[]&gt; vehiclesLocalCache;<br>    private final ServiceMetrics serviceMetrics;<br><br>    @Override<br>    public void onChange(String name) {<br>        if (vehiclesLocalCache.get(name) != null) {<br>            log.warn(&quot;Vehicle in remote cache updated : {}&quot;, name);<br>            // remove your local cache entry<br>            vehiclesLocalCache.remove(name);<br>            // update needed metrics<br>            serviceMetrics.incrementCacheTrackingListenerUpdateCount();<br>            serviceMetrics.setVehiclesLocalCache(vehiclesLocalCache.size());<br>            serviceMetrics.setVehiclesLocalCache(vehiclesLocalCache.sizeInMemory());<br>        }<br>    }<br>}</pre><p>There are also LocalCacheInvalidationListener and LocalCacheUpdateListener to listen to invalidation and updates on Local cache, which will be used to perform any side effects like logging, metrics, etc.</p><pre>import org.redisson.api.listener.LocalCacheInvalidationListener;<br><br>@Slf4j<br>@RequiredArgsConstructor<br>@Component<br>public class CustomCacheInvalidationListener implements <br>        LocalCacheInvalidationListener&lt;String, byte[]&gt; {<br><br>    private final ServiceMetrics serviceMetrics;<br><br>    @Override<br>    public void onInvalidate(String key, byte[] value) {<br>        if (vehiclesLocalCache.get(name) != null) {<br>            // aspects class that can be used to do more metrics on local cache invalidation<br>            log.warn(&quot;Vehicle in local cache removed : {}&quot;, name);<br>            serviceMetrics.incrementCacheInvalidationCounter();<br>        }<br>    }<br>}</pre><p>Key Points</p><ul><li>RESP3 Protocol is required for this to work with Redisson, Redisson automatically negotiates RESP3 if Redis ≥ 6 is detected; no extra code is required.</li><li>Supported only from Redis 6 and above</li></ul><p><strong>References</strong></p><ul><li><a href="https://redis.io/docs/latest/commands/client-tracking/">CLIENT TRACKING</a></li><li><a href="https://redisson.org/docs/client-side-caching/">Client-Side Caching</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77a44349a58c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sample Reactor Kafka Producer and Consumer with Spring boot in Kotlin]]></title>
            <link>https://blog.devgenius.io/sample-reactor-kafka-producer-and-consumer-with-spring-boot-in-kotlin-145b5f46e59e?source=rss-e88dd7601d3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/145b5f46e59e</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[reactor]]></category>
            <dc:creator><![CDATA[Seetha Wenner]]></dc:creator>
            <pubDate>Tue, 12 Jul 2022 14:42:34 GMT</pubDate>
            <atom:updated>2022-08-17T05:39:43.580Z</atom:updated>
            <content:encoded><![CDATA[<p>Created <a href="https://github.com/seetharamani/sample-reactor-kafka-springboot">sample-reactor-kafka-springboot</a> repository to show how to start a kafka consumer and producer using project-reactor and spring boot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*18LF7eb3ncJUfGTbKREyyQ.png" /><figcaption>@nasawebb</figcaption></figure><h3>Publisher Configuration</h3><p>Few things to note here are</p><ul><li>I have configured the publisher with keys of String datatype and values of ByteArray datatype, thus configured the StringSerializer and ByteArraySerializer in the SenderOptions</li><li>These configs are just for example purposes. Adjust them accordingly for your use case and load</li><li>Publisher topic are constructed only when the ProducerRecord is being constructed. Topic is not configured in the KafkaSender</li></ul><pre>@Component<br>@ConfigurationProperties(&quot;kafka&quot;)<br>class PublisherConfiguration {<br>    lateinit var kafkaBootstrapServers: String<br>    lateinit var clientId: String<br>    lateinit var publisherTopic: String<br>    lateinit var acks: String<br><br>    var maxRequestSize: Int = 0<br>    var retries: Int = 0<br>    var lingerMs: Int = 0<br>    var reconnectBackoffMs: Int = 0<br>    var retryBackoffMs: Int = 0<br>    var batchSize: Int = 16384<br><br>    // this is default, in general should be much less, <br>    // but &gt; replica.lag.time.max.ms<br>    var requestTimeoutMs: Int = 30 * 1000<br><br>    private fun getSenderOptions(): <br>SenderOptions&lt;String, ByteArray&gt; {<br>        val properties = Properties()<br>        properties[ProducerConfig.BOOTSTRAP_SERVERS_CONFIG] = kafkaBootstrapServers<br>        properties[ProducerConfig.CLIENT_ID_CONFIG] = clientId<br>        properties[ProducerConfig.ACKS_CONFIG] = acks<br>        properties[ProducerConfig.RETRIES_CONFIG] = retries<br>        properties[ProducerConfig.LINGER_MS_CONFIG] = lingerMs<br>        properties[ProducerConfig.MAX_REQUEST_SIZE_CONFIG] = maxRequestSize<br>        properties[ProducerConfig.RECONNECT_BACKOFF_MS_CONFIG] = reconnectBackoffMs<br>        properties[ProducerConfig.RETRY_BACKOFF_MS_CONFIG] = retryBackoffMs<br>        properties[ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG] = StringSerializer::class.java<br>        properties[ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG] = ByteArraySerializer::class.java<br>        properties[ProducerConfig.BATCH_SIZE_CONFIG] = batchSize<br>        properties[ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG] = requestTimeoutMs<br><br>        log.info(&quot;Kafka publisher properties configured : {}&quot;, properties)<br><br>        return SenderOptions.create(properties)<br>    }<br><br>    @Bean<br>    fun kafkaSender(<br>           publisherConfiguration: PublisherConfiguration<br>        ): KafkaSender&lt;String, ByteArray&gt; {</pre><pre>        return KafkaSender.create(<br>             publisherConfiguration.getSenderOptions()<br>             )<br>    }<br><br>    companion object {<br>        private val log = LoggerFactory<br>                 .getLogger(PublisherConfiguration::class.java)<br>    }<br>}</pre><h3>Receiver Configuration</h3><p>Fews things to note here are</p><ul><li>Make sure set the group id for your receiver</li><li>I have configured the publisher with keys of String datatype and values of ByteArray datatype, thus configured the StringDeserializer and ByteArrayDeserializer in the ReceiverOptions</li><li>These configs are just for example purposes. Adjust them accordingly for your use case and load</li><li>Topics to consume from are configured as part of KafkaReceiver</li></ul><pre>@Component<br>@ConfigurationProperties(&quot;kafka&quot;)<br>class ReceiverConfiguration {<br><br>    lateinit var kafkaBootstrapServers: String<br>    lateinit var groupId: String<br>    lateinit var clientId: String<br>    lateinit var receiverTopic: String<br>    lateinit var autoOffsetReset: String<br><br>    var concurrency: Int = 1<br>    var maxPollTimeoutMs: Int = 10000<br>    var backtrackTimeSeconds: Int = 15 * 60<br><br>    var retryBackoffMs: Int = 1000<br>    var maxPollRecords: Int = 250<br>    var maxPollIntervalMs: Int = 300_000<br>    var sessionTimeoutMs: Int = 10_000<br>    var heartbeatIntervalMs: Int = 3000<br>    var requestTimeoutMs: Int = 30_000<br>    var autoCommitIntervalMs: Int = 5000<br>    var commitBatchSize: Int = 0<br>    var commitIntervalMs: Long = 5000L<br><br>    fun getReceiverOptions(): ReceiverOptions&lt;String?, ByteArray&gt; {<br>        val properties = Properties()<br>        properties[ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG] = kafkaBootstrapServers<br>        properties[ConsumerConfig.GROUP_ID_CONFIG] = groupId<br>        properties[ConsumerConfig.CLIENT_ID_CONFIG] = clientId<br>        properties[ConsumerConfig.RETRY_BACKOFF_MS_CONFIG] = retryBackoffMs<br>        properties[ConsumerConfig.AUTO_OFFSET_RESET_CONFIG] = autoOffsetReset<br>        properties[ConsumerConfig.MAX_POLL_RECORDS_CONFIG] = maxPollRecords<br>        properties[ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG] = maxPollIntervalMs<br>        properties[ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG] = sessionTimeoutMs<br>        properties[ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG] = heartbeatIntervalMs<br>        properties[ConsumerConfig.REQUEST_TIMEOUT_MS_CONFIG] = requestTimeoutMs<br>        properties[ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG] = StringDeserializer::class.java<br>        properties[ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG] = ByteArrayDeserializer::class.java<br>        properties[ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG] = autoCommitIntervalMs<br><br>        log.info(&quot;Kafka receiver properties configured : {}&quot;, properties)<br><br>        return ReceiverOptions.create&lt;String?, ByteArray&gt;(properties)<br>            .commitInterval(Duration.ofMillis(commitIntervalMs))<br>            .commitBatchSize(commitBatchSize)<br>    }<br><br>    @Bean<br>    fun kafkaReceiver(receiverConfiguration: ReceiverConfiguration): KafkaReceiver&lt;String, ByteArray&gt; {<br>        return KafkaReceiver.create&lt;String, ByteArray&gt;(<br>            receiverConfiguration.getReceiverOptions().subscription(<br>                listOf(<br>                    receiverTopic<br>                )<br>            )<br>        )<br>    }<br><br><br>    companion object {<br>        private val log = LoggerFactory.getLogger(ReceiverConfiguration::class.java)<br>    }<br>}</pre><h3>Starting and stopping the consumer</h3><p>kafkaReceiver.receive().subscribe() starts the consumer and having it in the PostConstruct of the Workflow class makes sure the receiver starts consuming messages once the application context get loaded and the bean creation is completed.</p><pre>private val disposables = Disposables.composite()<br><br>@PostConstruct<br>fun connect() {<br>    disposables.add(<br>        receive()<br>            .subscribe(<br>                <strong>{ </strong>log.info(&quot;Ended subscription to Kafka Receiver&quot;) <strong>}</strong>,<br>                <strong>{ </strong>err <strong>-&gt; </strong>log.error(&quot;Error in Kafka Receiver flow&quot;, err) <strong>}<br>            </strong>)<br>    )<br>}<br><br>@PreDestroy<br>fun disconnect() {<br>    this.disposables.dispose()<br>}</pre><h3>Integration Test</h3><p>With EmbeddedKafka annotation configure the IT test with input and output topics</p><pre>@EmbeddedKafka(<em><br>    </em>partitions = 1,<br>    topics = [&quot;input&quot;, &quot;output&quot;]<br>)</pre><p>Apart from the KafkaReceiver and KafkaSender we created in the PublisherConfiguration and ReceiverConfiguration classes we need a test kafka sender to publish messages to the input topic to test the Workflow app Test kafka sender is configured in @BeforeClass setup just like the other kafka sender which publishes to output topic.</p><p>Since the kafka receiver is started right after application start up we need to make sure to disconnect the receiver in @BeforeEach This way, we can have the receiver subscribed in our test case for actual validation.</p><pre>@BeforeEach<br>fun setUp() {<em><br>    </em>workflow.disconnect()<br>}</pre><p>Finally disposing the subscriber after validation as part of the test.</p><p>Full project here — <a href="https://github.com/seetharamani/sample-reactor-kafka-springboot">https://github.com/seetharamani/sample-reactor-kafka-springboot</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=145b5f46e59e" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/sample-reactor-kafka-producer-and-consumer-with-spring-boot-in-kotlin-145b5f46e59e">Sample Reactor Kafka Producer and Consumer with Spring boot in Kotlin</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Safepoint and Async Profiling]]></title>
            <link>https://seethawenner.medium.com/java-safepoint-and-async-profiling-cdce0818cd29?source=rss-e88dd7601d3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdce0818cd29</guid>
            <category><![CDATA[profiling]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[flamegraphs]]></category>
            <dc:creator><![CDATA[Seetha Wenner]]></dc:creator>
            <pubDate>Sun, 14 Feb 2021 22:03:12 GMT</pubDate>
            <atom:updated>2021-02-14T22:03:12.676Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*BsOVPPDRtqaUjun33rGlIA.gif" /></figure><p>While deep into the woods of Java lot of times most developers have faced performance issue with their application. Even with microservices, though the complexity of the application is small, it can still suffer from performance issues like, too much computation processing going on, or DB calls taking too long, or lot of IO happening all the time.</p><p>Java profiling helps you debug these kind of issues if you wanted to know</p><ul><li>CPU utilization</li><li>Memory utilization/ memory leak</li><li>Are there any deadlock scenarios, etc</li></ul><p>While java does provide default tooling for CPU profiling and memory profiling most of the time profiling your application in staging/production has the danger of bringing your entire application down due to the overhead involved in profiling. Async profiling is a low overhead sampling profiler for Java that does not suffer from <strong>Safepoint bias problem</strong>. It features HotSpot-specific APIs to collect stack traces and to track memory allocations. The profiler works with OpenJDK, Oracle JDK and other Java runtimes based on the HotSpot JVM.</p><p>Before we talk about why async profiling, we need to know what is the safepoint bias problem is! Before we talk about that problem we need to understand what is safepoint is!!!</p><p>So..Let’s talk to a java thread to understand these questions! ✋</p><h3>What is a Safe point?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lmqnayAsz0dnjGcATvawqQ.png" /></figure><p>At safepoint,</p><ul><li>I know my exact state in my interaction with the heap</li><li>all my references on the stack are mapped</li><li>JVM can account for all my references</li><li>thank you JVM! My view of the world remains consistent at this “safe point”</li><li>I am blocked at a safe point that no body can pull me for any other tasks</li></ul><h3>When is a thread at a safe point?</h3><p>I am at a safepoint when I am doing these ⬇️ tasks!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pJoeDOL-zS-m9XmAYtAhxg.png" /></figure><ul><li>All these events are qualified as orderly de-scheduling events for the Java thread</li><li>as part of tidying things up before put on hold, the threads are brought to a safe point</li></ul><p>Also please know that I am not at a safepoint when I am doing these ⬇️ tasks!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cApcYFN5T_pEJ4LIFxi-Kw.png" /></figure><h3>JVM — Threads relationship 💞</h3><p>Only if every relationship is this perfect!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9s5HCruhP_OF5motqeYXbw.png" /></figure><h3>Bringing a thread to safe point</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eAYszY8kqSpB_AO94ijB0w.png" /></figure><ul><li>threads poll for safe point flag at “reasonable” intervals</li><li>they transition them into safe points when they observe “go to safe point flag”</li><li>keep the polling interval at minimum since that would add significant overhead and we don’t want to spend all the time checking if we need to stop the C1/C2 compilers</li><li>on top of this, maintaining a “known state” add more complexity as well</li></ul><p>So keeping these in mind, safe point polls are done at these locations</p><ul><li>Between any 2 byte codes while running in the interpreter</li><li>On “non-counted” loop back edge in C1/C2 compiled code</li><li>Method entry/exit in C1/C2 compiled code</li></ul><h3>What is a safepoint bias problem?</h3><p>Most profilers are limited to safepoint sampling. You hit a global safepoint whether you are sampling a single thread or all threads. So this adds up to setting up a timer thread which triggers at sampling_interval and gathers all stack traces. This is bad for several reasons</p><ul><li>Sampling profilers need samples! So it is common to set the sampling frequency pretty high. Say for example a profiler is sampling 10 times a second or every 100ms, and it creates 5ms pause to do its job depending on the depth of the stack trace, number of threads, etc., So a 5ms pause every 100ms means 5% overhead introduced by profiling. Even if you set the frequency interval longer you need to profile for longer time to get any meaningful sampling count!</li><li>Gathering full stack traces from all your threads means the cost of profiling is open ended.</li><li>The worst thing of all is, profilers are trying to sample threads at safepoint to avoid these overheads, but in reality you would want to sample the threads which are actually doing something rather than spending all of their time blocked!</li></ul><p>So what does sampling at a safepoint mean? It means only the safepoint polls in the running code are visible. Given hot code is likely compiled by C1/C2 (client/server compilers) we have reduced our sampling opportunities to method exit and uncounted loop back edges. This leads to the phenomena called <strong>safepoint bias</strong> whereby the sampling profiler samples are biased towards the next available safepoint poll location This fails the criteria set out for an ideal profiler that — “<strong>the profiler should sample all points in a program run with equal probability</strong>”</p><p>Now after knowing what a safepoint is and how most profilers are suffering from safe point bias problem, using Async profiler makes much more sense. You can read more about <a href="https://github.com/jvm-profiling-tools/async-profiler">async profiler in their Github page</a>.</p><p>Here is some shell scripting to create short cuts to take async profiling from kubernetes pods.</p><ul><li>async-profiling.sh</li></ul><pre><strong>#!/bin/bash<br></strong>if [$# -ne 1 ]; then<br>  echo &gt;&amp;2 &quot;Usage: $0 [ &lt;duration-in-seconds&gt; ]&quot;<br>  exit 1<br>fi<br><br># Install async-profiler <br>if [! -f &quot;./profiler.sh&quot; ]; then<br>  curl -L https://github.com/jvm-profiling-tools/async-profiler/releases/download/v1.8.1/async-profiler-1.8.1-linux-x64.tar.gz &gt; async.tar.gz<br>  tar xfvz async.tar.gz<br>fi<br><br>rm -f flame.svg<br>echo &quot;profiling for $1 seconds...&quot;</pre><pre>./async-profiler-1.8.1-linux-x64/profiler.sh -d &quot;$1&quot; -f $<em>(</em>pwd<em>)</em>/flame.svg 1 --all-user -e alloc</pre><ul><li>Executing inside a k8s pod to run async profiling</li></ul><pre>function kubectl_async_profiling_single_pod() {<em><br>  </em>if [$# -ne 2 ]; then<br>    echo &quot;Usage $0 &lt;pod-name&gt; [ &lt;duration-in-seconds&gt; ]&quot;<br>    echo &quot;Make sure to execute from the directory where async-profiling.sh file exists&quot;<br>    echo &quot;Example $0 pod_name 120&quot;<br>    echo &quot;&quot;<br>    return 1<br>  fi<br>  if [! -f &quot;async-profiling.sh&quot; ]; then<br>    echo &quot;Make sure to execute from the directory where async-profiling.sh file exists&quot;<br>    echo &quot;Exiting...&quot;<br>    return 1<br>  fi<br><br>  filename=&quot;$1-$<em>(</em>date +&#39;%m-%d-%Y-%H-%M-%S&#39;<em>)</em>-flame.svg&quot;<br>  echo &quot;Executing on pod $1&quot;<br>  kubectl cp async-profiling.sh alfa/&quot;$1&quot;:.<br>  kubectl exec &quot;$1&quot; chmod +x async-profiling.sh<br>  kubectl exec &quot;$1&quot; ./async-profiling.sh &quot;$2&quot;<br>  kubectl cp alfa/&quot;$1&quot;:flame.svg ./output/&quot;$filename&quot;<br>  echo &quot;Downloaded $filename&quot;<br>}</pre><pre>kubectl_async_profiling_single_pod &lt;pod-name&gt; &lt;duration-in-seconds&gt; </pre><pre>Example --&gt; kubectl_async_profiling_single_pod my-k8s-app-8678f86c5f-5jvpt 600</pre><p>This will create the flame svg file in the format pod-name-MM-DD-YYYY-HH-SS-MM-flame.svg in ./output folder</p><h3>How to interpret a flame graph?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCvRkOm4JVmnrOHaFUYjOg.png" /></figure><p>Read it from bottom-up.</p><ul><li>a() calls b() and h()</li><li>b() calls c()</li><li>c() calls d() and so on..</li><li>Flame graph is alphabetically ordered not ordered by the time it took for each method — notice e() and f()</li><li>Flame graph don’t have timestamps. We just know b() executed longer than h()</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FDGItwWRiJ_09xBJsz3CtQ.png" /></figure><ul><li>here g() is consuming the most CPU cycles</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2AdaFC2vnOdnrkd-ntJfGg.png" /></figure><ul><li>while looking to optimize g() we might need to look at the stack call for g() and see where the optimization can be done</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I0alEzsCA-z7qbBtPrDFYw.png" /></figure><h3>References</h3><ul><li><a href="https://github.com/jvm-profiling-tools/async-profiler">https://github.com/jvm-profiling-tools/async-profiler</a></li><li><a href="https://github.com/BrendanGregg/FlameGraph">https://github.com/BrendanGregg/FlameGraph</a></li><li><a href="http://www.brendangregg.com/flamegraphs.html">http://www.brendangregg.com/flamegraphs.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdce0818cd29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improve the performance of your AWS RDS Postgres Database by avoiding Session Pinning]]></title>
            <link>https://seethawenner.medium.com/improve-the-performance-of-your-aws-rds-postgres-database-by-avoiding-session-pinning-a4f010109bed?source=rss-e88dd7601d3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4f010109bed</guid>
            <category><![CDATA[database-performance]]></category>
            <category><![CDATA[jdbc]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[pinning]]></category>
            <category><![CDATA[rds]]></category>
            <dc:creator><![CDATA[Seetha Wenner]]></dc:creator>
            <pubDate>Thu, 13 Aug 2020 15:02:33 GMT</pubDate>
            <atom:updated>2020-08-13T15:02:33.863Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RFBAH7E834S6AzJNsiJv2A.gif" /></figure><h3>What do I have in the application?</h3><p>It just started as a simple microservice to persist some data and generate metrics around it. But as with any project many features were added over time to the application like quartz schedulers with simple triggers which also uses the database to store job details and triggers.</p><p>A complicated query runs against a view every 15 seconds to collect metrics. Obviously our first thought was tuning that massive complex query. The database schema itself is not complicated. After creating indexes around the columns used in the where clause, there was still no improvement in performance .</p><p>The explain plan of the query shows that execution time of the query is at around 30s which is not the greatest, but while tracking the query latency through application, it was almost at more than a minute.</p><p>Pro tip — With Hikari you can set a time limit for the the leak-detection-threshold property allowing you to see when a connection takes more than the set amount of time.</p><h3>How did I identify the issue?</h3><p>While trying to take a stab at the query performance, I monitored the cloud watch RDS metrics from AWS and noticed insane amount of write iOPS and read iOPS. The application itself is simple that for every transaction, would expect 3 writes to the database. Request per seconds was at around ~40RPS. So the expectation is to have 40 * 3 = 120 write iOPS, but were seeing around 2K iOPS, which is insanely high.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_kISFOgf6FL002lsRaenbw.png" /></figure><p>This DB performance degradation was causing a cascading effect that, the application’s processing speed slowed down. This resulted in a kafka lag because producers were producing faster than it could be consumed— till it gets to a point that everything get choked up and hang.</p><p>Now we have to find why there are so many writes?!</p><p>The backend’s most recent query can be found in the pg_stat_activity view query column. If state is active then the query field shows the currently executing query. In all other states, it shows the last query that was executed.</p><p>Out of 120 total connections almost 115 of them were executing the query SET application_name = &quot;PostgreSQL JDBC Driver&quot;</p><p>There is our problem! Before we dive in on how to fix this issue we need to understand some basic concepts with RDS proxy.</p><h3>What is Session Pinning?</h3><p>AWS RDS Proxy handles the infrastructure for connection pooling. Each proxy handles connections to a single RDS DB instance or Aurora DB cluster. These set of connections that a proxy keeps “open and available” for your database application to use, form the connection pool</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oK3WgCiGy8RSnH9hUB9K-w.png" /></figure><p>All the statements within a single transaction always use the same underlying database connection. The connection becomes available for use by a different session when the transaction ends.</p><p>By default, RDS Proxy can reuse a connection after each transaction in your session. This transaction-level reuse is called multiplexing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*WgfWGN6125YVQ7YCwid8-Q.png" /></figure><p>When RDS Proxy temporarily removes a connection from the connection pool to reuse it, that operation is called borrowing the connection. When it’s safe to do so, RDS Proxy returns that connection to the connection pool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*yQto-SXNodGGuY2NAEyK-A.png" /></figure><p>In some cases, RDS Proxy can’t be sure that it’s safe to reuse a database connection outside of the current session. In these cases, it keeps the session on the same connection until the session ends. This fallback behavior is called pinning</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*NZWMpU-qK2XuBMNTwX3w9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*ulY_6KLNFpUeEOOBn-9TgQ.png" /></figure><p>By default, RDS Proxy detects when a transaction ends through the network protocol used by the database client application. Transaction detection doesn’t rely on keywords such as COMMIT or ROLLBACK appearing in the text of the SQL statement.</p><p>In some cases, RDS Proxy might detect a database request that makes it impractical to move your session to a different connection. In these cases, it turns off multiplexing for that connection for the remainder of your session. The same rule applies if RDS Proxy can’t be certain that multiplexing is practical for the session.</p><p>RDS Proxy automatically pins a client connection to a specific DB connection when it detects a session state change that isn’t appropriate for other sessions. Pinning reduces the effectiveness of connection reuse. If all or almost all of your connections experience pinning, consider modifying your application code or workload to reduce the conditions that cause the pinning.</p><h3>How does the problem get resolved?</h3><p>In my particular use case, I could see from pg_stat_activity table that, trying to SET the application name so often is the cause for pinning. Setting this parameter at the JDBC driver as a connection parameter will prevent the JDBC driver from performing an extra round trip during connection startup.</p><p>You can set this parameter at the url like this</p><pre>jdbc:postgresql://myapplication-2020123456789.somedomain.region.rds.amazonaws.com:5432/dbname?ApplicationName=myapplicationname</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sOLprwzM9KVjBy1VZSTZcQ.png" /></figure><h3>Other causes of pinning and how to identify and avoid them?</h3><ul><li>Any statement with a text size greater than 16KB cause the proxy to pin the session — avoid unnecessary database requests and be cautious of request size</li><li>Using prepared statements, setting parameters, or resetting a parameter to its default — Set the JDBC connection parameter preferQueryMode to extendedForPrepared to avoid pinning. The extendedForPrepared ensures that the extended mode is used only for prepared statements</li><li>Setting a user variable or a system variable (with some exceptions) causes the proxy to pin the session — set these variables as connection parameter at the JDBC url to avoid extra round trips. For example in PostgreSQL when using JDBC set the JDBC connection parameter assumeMinServerVersion to at least 9.0 to avoid pinning. Doing this prevents the JDBC driver from performing an extra round trip during connection startup when it runs SET extra_float_digits = 3</li><li>Creating a temporary tables, sequences or views causes the proxy to pin the session</li><li>Declaring cursors</li><li>Discarding the session state</li><li>Listening on a notification channel</li><li>Loading a library module such as auto_explain</li><li>Manipulating sequences using functions such as nextval() and setval()</li><li>Interacting with locks using functions such as pg_advisory_lock() and pg_try_advisory_lock()</li></ul><p>Reference — <a href="https://docs.aws.amazon.com/es_mx/AmazonRDS/latest/UserGuide/rds-proxy.html#rds-proxy-pinning">https://docs.aws.amazon.com/es_mx/AmazonRDS/latest/UserGuide/rds-proxy.html#rds-proxy-pinning</a></p><p>Thanks to <a href="https://medium.com/u/d61c1d3513fc">Matt</a> for reviewing the blog!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4f010109bed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[User-land Threads vs Native Threads]]></title>
            <link>https://seethawenner.medium.com/user-land-threads-vs-native-threads-b45f3150be0b?source=rss-e88dd7601d3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b45f3150be0b</guid>
            <category><![CDATA[parallelism]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Seetha Wenner]]></dc:creator>
            <pubDate>Tue, 18 Feb 2020 20:18:42 GMT</pubDate>
            <atom:updated>2020-02-18T20:18:42.659Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*Bttgb0C_weyZIaTIyCCTpQ.png" /></figure><h3>Native threads</h3><ul><li>Native threads are threads schedule by the kernel, in particular they use the pthread library and have access to the kernel space</li><li>Kernel with the knowledge of underlying OS are aware of native threads</li><li>These threads have full access to the Kernal space</li><li>Kernel requires a full thread control block (TCB) for each thread to maintain information about threads like time slice and the cursor position of the task for the scheduler to resume the execution, they have significant overhead and the context switching is expensive</li><li>Most of the time these threads are specific to the underlying OS implementation and so they are not portable</li></ul><h3>UserLand Threads</h3><ul><li>User-land threads aka User-level threads aka green threads are scheduled by the execution environment like JVM, runtime, etc without relying on any native OS capabilities</li><li>Execution environment and the underlying OS doesn’t recognize these threads</li><li>It has access only to the user space and will not have access to kernel space i.e, the kernel have no knowledge of these threads and treat them like a single process</li><li>User-land threads are pretty lightweight and so the context switching is relatively easy and cheap</li><li>Due to their simple management and representation they are faster and efficient</li><li>These threads are managed by the user program and are not dependent on the scheduler implementation of the underlying OS. So they are portable and can be used in simple kernel, which doesn’t support thread scheduling</li></ul><h3>Multiprocessing environment</h3><p>As you can see in the pictures below, native threads can achieves parallelism through multiprocessing CPUs or cores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*multzZbRqdulJsdslbYQYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s-DQKgxFNnyOSImyZcJZyA.png" /></figure><p>User-land threads have scope only inside a single cpu. Modern languages are attempting for a hybrid approach of user-land thread’s concurrency along with native thread’s parallelism.</p><h3>Context Switching</h3><p>Native threads can switch between threads pre-emptively, switching control from a running thread to a non-running thread at any time. But this comes with the cost of suspending the state of the thread, and the cost of switching between user mode (for the thread) and kernel mode (for the scheduler).</p><p>User-land threads only switch when the control is explicitly given up by a thread or when a thread performs a blocking operation.If a process schedules its own threads directly and cooperatively, the context switch to kernel mode is unnecessary, and switching tasks is quite cheap.</p><h3>Blocking call</h3><p>As most of you know, threads have to make system call to perform blocking operations like IO. User-Level threads are not a perfect solution as with everything else, they are a trade off. Since, User-Level threads are invisible to the OS they are not well integrated with the OS. As a result, OS can make poor decisions like scheduling a process with idle threads, blocking a process whose thread initiated an I/O even though the process has other threads that can run and unscheduling a process with a thread holding a lock. Solving this requires communication between between kernel and user-level thread manager.</p><p>There is a lack of coordination between threads and operating system kernel. Therefore, process as whole gets one time slice irrespective of whether process has one thread or 1000 threads within. It is up to each thread to relinquish control to other threads.</p><p>User-level threads requires non-blocking systems call i.e., a multithreaded kernel. Otherwise, entire process will be blocked in the kernel, even if there are runnable threads left in the processes. For example, if one thread causes a page fault, the process blocks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1nxZ5M_Fo2yChdPtzQHo2w.png" /></figure><p>Java green threads implementations did not scale over multiple cores or CPUs and was deprecated due to the complexities for the developers to manage the implementation of user space scheduler.</p><p>Modern languages like Erlang, Go has the runtime to manage the user level threads and they are a lot better for concurrency and parallelism. Keep in mind that green threads from Java are a lot different from coroutines and coroutines are a lot different from goroutines. This will be a topic for itself to go in depth! Happy Threading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b45f3150be0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>