<?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 Shrey Garg on Medium]]></title>
        <description><![CDATA[Stories by Shrey Garg on Medium]]></description>
        <link>https://medium.com/@shr8bit?source=rss-3cba0919e898------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*smi0OUM9smMUTTQkeB3clQ.jpeg</url>
            <title>Stories by Shrey Garg on Medium</title>
            <link>https://medium.com/@shr8bit?source=rss-3cba0919e898------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:26:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shr8bit/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 OkCredit Android App boosted Network Performance by 30%]]></title>
            <link>https://medium.com/okcredit/how-okcredit-android-app-boosted-network-performance-by-30-84109080c065?source=rss-3cba0919e898------2</link>
            <guid isPermaLink="false">https://medium.com/p/84109080c065</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[okcredit]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Shrey Garg]]></dc:creator>
            <pubDate>Thu, 07 Jul 2022 11:29:22 GMT</pubDate>
            <atom:updated>2022-07-07T11:29:22.754Z</atom:updated>
            <content:encoded><![CDATA[<p>Fast and reliable network communication is crucial for OkCredit mobile apps. Since the majority of our users belong to Tier-2/3 cities in India, flaky and unreliable network connection is one of the biggest challenges for us. In order to deliver a good user experience, our mobile apps need to have reliable and low-latency network connectivity.</p><p>While most resources we found describe how we can improve the overall time (start-end) of a network call, this article attempts to take a deep dive and talk about each step and how we can instrument and optimise each step of a network call in android apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pk1d0x6_S-ykvmtyHHl8RA.png" /></figure><h3>Steps involved in a network call</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xWQLL5zVemhDe44VK5yHpQ.png" /><figcaption>Fig. Steps of a Network call. Ref — <a href="https://square.github.io/okhttp/features/events">https://square.github.io/okhttp/features/events</a></figcaption></figure><h4><strong>1. Call start</strong></h4><p>Called as soon as a call is enqueued or executed by a client. Ideally, this step should not consume any time unless there are any custom <a href="https://square.github.io/okhttp/features/interceptors/">Interceptors</a> added.</p><h4><strong>2. DNS</strong></h4><p>Involves the DNS Resolver translating the domain name into the corresponding identifier (the IP address).</p><h4><strong>3. Connection Start</strong></h4><p>Tries to acquire a secure connection (<a href="https://square.github.io/okhttp/4.x/okhttp/okhttp3/-handshake/">TLS handshake</a>) between the client and the server.</p><h4><strong>4. Connection End / Acquired</strong></h4><p>Invoked after a connection has been acquired for the call. After this, the communication of request and response payloads is started.</p><h4><strong>5. Request / Response / Headers</strong></h4><p>This is the step in which the actual communication of data happens. The <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods">HTTP method</a>, size of request / response payload, <strong>server latency / response time</strong>, etc. can greatly impact the time taken by this step.</p><h4><strong>6. Connection released</strong></h4><p>Invoked after a connection has been released for the call.</p><h4><strong>7. Call end</strong></h4><p>Invoked immediately after a call has completely ended.</p><h3>Pooled connection</h3><p><a href="https://square.github.io/okhttp/">OkHttp</a> has the capability to <a href="https://square.github.io/okhttp/3.x/okhttp/okhttp3/ConnectionPool.html">pool connections</a> with which it can skip various steps of a network call mentioned above, which in turn can greatly improve the application’s network performance, as existing connections can be reused.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q2w5wKNEvDIoxqGxmJTyCA.png" /><figcaption>Fig. Steps of a Network call with pooled connection</figcaption></figure><h3>Instrumentation of each step</h3><p>To determine the particular step(s) having a scope of improvement, we can instrument each step to know exactly how much time it is taking.</p><p>We can make use of the <a href="https://square.github.io/okhttp/3.x/okhttp/okhttp3/EventListener.html">EventListener</a> class for listening to metrics for each step. EventListener is an abstract class for metrics events. We can monitor the quantity, size and duration of HTTP calls. It is recommended that the metric callback methods should be <strong>lightweight</strong>, execute <strong>fast</strong> and perform any I/O operations <strong>asynchronously</strong>.</p><p>By overriding various callback methods, we can calculate the metrics for each step of a network call efficiently. Some of the important methods that can be overridden are :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ig7ETYu0ZTuBGe207q317g.png" /><figcaption>Some important callback methods to be overridden for metrics</figcaption></figure><p>Note — there are a few more callbacks that can be used for detailed metric analysis.</p><h4>Instrumenting on Production</h4><p>There can be various factors affecting network performance on production. Instrumenting in a controlled environment might not give the actual metrics, hence, rather than testing network performance using local tools, it might be a good idea to enable instrumentation on a <a href="https://en.wikipedia.org/wiki/Sampling_(statistics)">sampled</a> set of production users.</p><p>This can give metrics across various types of environments, such as :</p><ul><li>Network operators / Wifi</li><li>Geographical regions</li><li>Device manufacturers</li><li>Application state (Background/Foreground)</li><li>Android OS version, etc.</li></ul><h3>Calculation of network performance metrics</h3><p>Time taken by different events, eg. connection start -&gt; connection end, request body start -&gt; request body end, etc., can be calculated by checking the difference between the start and end callback of that event. All start, connect, and acquire events will eventually receive a matching end, release event, either successful or failed.</p><p>An example of the same is shown below :</p><pre>class NetworkCallEventListener : EventListener() {<br>    private var callStartMillis: Long<br><br>    private fun printEvent(eventName: String) {<br>        val currentTimestamp = System.currentTimeMillis()<br>        if (eventName == &quot;callStart&quot;) {<br>            callStartMillis = currentTimestamp<br>        }<br>        val elapsedMillis = currentTimestamp - callStartMillis<br>        <em>println</em>(&quot;$elapsedMillis ms : $eventName&quot;)<br>    }<br><br>    override fun callStart(call: Call) {<br>        printEvent(&quot;callStart&quot;);<br>    }<br><br>    override fun callEnd(call: Call) {<br>        printEvent(&quot;callEnd&quot;);<br>    }<br><br>}</pre><p>The gist mentioned below can be used for logging network performance metrics :</p><blockquote><a href="https://gist.github.com/okshrey/fbe6349b888eba4c36e73745f9c5d2e0"><strong>https://<em>gist.github.com</em>/okshrey/fbe6349b888eba4c36e73745f9c5d2e0</strong></a></blockquote><h4>Usage</h4><p>Create an instance of <a href="https://gist.github.com/okshrey/fbe6349b888eba4c36e73745f9c5d2e0"><em>NetworkCallEventListener.kt</em></a> in <a href="https://square.github.io/okhttp/4.x/okhttp/okhttp3/-ok-http-client/-builder/event-listener-factory/"><em>eventListenerFactory</em></a> inside OkHttpClient.Builder(), as shown below —</p><pre>OkHttpClient<br>    .Builder()<br>    .<em>apply </em><strong>{<br>        </strong>eventListenerFactory <strong>{ <br>            </strong>NetworkCallEventListener(analyticsProvider) <br>        <strong>}<br>        </strong>callTimeout(...)<br><strong>        </strong>...<br>     <strong>}</strong></pre><h3>Areas of improvement we identified</h3><h4>- Use a single instance of OkHttp throughout the app</h4><p>In a multi-module android application, a common mistake is to create multiple OkHttp instances for each module. Doing so can be detrimental to the network performance, since each OkHttp instance will have a separate connection pool, and will not be able to take advantage of a pooled connection present at another instance.</p><h4>- Fine-tune OkHttp Connection Pool</h4><pre>class ConnectionPool constructor(<br>    maxIdleConnections: Int,<br>    keepAliveDuration: Long,<br>    timeUnit: TimeUnit<br>)</pre><p>Optimal values for <em>keepAliveDuration</em> and <em>maxIdleConnections</em> can substantially improve network performance, as existing connections can be reused. The value for <em>keepAliveDuration</em> should ideally be the same at the client and server for optimal results. Use OkHttp Connection Pool with caution, having too high values for maxIdleConnections, keepAlive might end up in wastage of resources.</p><p>Since the connection step occurs at the client, its instrumentation cannot be done on the server. Hence, instrumenting and optimising it at the client is crucial.</p><h4>- Avoid I/O operations in Interceptors</h4><p>There are a lot of operations apps might want to perform in network interceptors. While having lightweight operations is fine, any kind of I/O operation should be avoided. A common practice that might lead to poor network performance, is attaching Authentication Tokens (retrieved using an I/O operation) to network requests.</p><h4>- Avoid having multiple API hosts</h4><p>When using microservice architecture, often different microservices can have different API host names, which will in turn require the app to call APIs at different hosts for each use case. Using multiple hosts in the app might result in the DNS step taking a longer time. To optimise this, it is recommended to have a single API host.</p><h4>- Auto-retry call on API failure</h4><p>To avoid non-idempotent API failures, such as timeout, server error, etc, a recommended trick is to add an Interceptor with automatic retries on API failures. This can be further improved by adding special handling for specific types of failures and adding appropriate delays in between retries.</p><h4>- Use QUIC</h4><p><a href="https://blog.cloudflare.com/the-road-to-quic/">QUIC</a> is a​ UDP-Based Multiplexed and Secure Transport. Using QUIC can optimise the connection acquisition step. Few apps like <a href="https://eng.uber.com/employing-quic-protocol/">Uber</a>, YouTube have been using QUIC and have seen improved network performance. Unfortunately, till the time of writing this article, <a href="https://github.com/square/okhttp/issues/907">OkHttp has not added support for QUIC</a>. An alternative that can be used is <a href="https://github.com/google/cronet-transport-for-okhttp/blob/master/README.md">Cronet</a>.</p><h4>- Adjusting DNS TTLs</h4><p>DNS TTL (Time To Live) is a setting that tells the DNS resolver how long to cache a query before requesting a new one. The information received is cached in the recursive or local resolver for the time specified in the TTL before it reaches out for new / updated details. Fine-tune this value so that the frequency for querying is minimised and updates are quickly propagated.</p><p>Other potential action items —</p><ul><li>Identify and fix <strong>high-latency</strong> APIs</li><li>Add <strong>Pagination</strong> to APIs</li><li>Use <a href="https://github.com/google/brotli"><strong>Brotli</strong></a> instead of Gzip compression</li><li>Test with <strong>hardcoded</strong> IP address</li><li><a href="https://square.github.io/okhttp//features/caching/">Response caching</a></li><li><a href="https://square.github.io/retrofit/2.x/retrofit/retrofit2/Converter.Factory.html">Converter Factory</a> — Use <strong>Moshi</strong> instead of Gson</li></ul><h3>Overall Impact</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B2k_mCAtRmALeWUrXiT0BA.png" /><figcaption>Before and after comparison of average time taken by network calls</figcaption></figure><p>After implementing some of the action items mentioned before, we were able to see an overall improvement of about <strong>30% </strong>in the average time taken by network calls, with a major improvement of <strong>70%</strong> in the Connection Start to Connection Acquired step.</p><p>Most engineers consider network performance as something that can only be optimised at the backend, however, there are plenty of optimisations that can be made at the client, that can critically impact the network performance.</p><blockquote>Credits to the entire Android team at OkCredit for making the OkCredit app better everyday — <a href="https://medium.com/u/6bd3bb208cdf">Nishant Shah</a>, <a href="https://medium.com/u/f16393a53557">Rashanjyot Singh</a>, <a href="https://medium.com/u/a444e64946c0">Mohitesh</a>, <a href="https://medium.com/u/71a420fd12b1">Harshitfit</a>, <a href="https://medium.com/u/2cf3c5aea38f">Pratham Arora</a>, <a href="https://medium.com/u/894b3b833587">Manas Yadav</a>, <a href="https://medium.com/u/a1273217c219">Saket Dandawate</a>, <a href="https://medium.com/u/cf6b0c2affc4">Anjal Saneen</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84109080c065" width="1" height="1" alt=""><hr><p><a href="https://medium.com/okcredit/how-okcredit-android-app-boosted-network-performance-by-30-84109080c065">How OkCredit Android App boosted Network Performance by 30%</a> was originally published in <a href="https://medium.com/okcredit">OkCredit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>