<?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[Incognia Tech Blog - Medium]]></title>
        <description><![CDATA[Notes on Data Science, Data Engineering, Backend and Product Development. - Medium]]></description>
        <link>https://medium.com/incognia-tech?source=rss----5b0cf5e0b18a---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Incognia Tech Blog - Medium</title>
            <link>https://medium.com/incognia-tech?source=rss----5b0cf5e0b18a---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:02:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/incognia-tech" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using Location as a Signal to Affirm Identity Online]]></title>
            <link>https://medium.com/incognia-tech/using-location-as-a-signal-to-affirm-identity-online-c01d35660a35?source=rss----5b0cf5e0b18a---4</link>
            <guid isPermaLink="false">https://medium.com/p/c01d35660a35</guid>
            <dc:creator><![CDATA[Roberto Colecchia]]></dc:creator>
            <pubDate>Thu, 30 Jun 2022 19:25:58 GMT</pubDate>
            <atom:updated>2022-06-30T19:25:58.279Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xZa78k6gAM7afR3qpEBSeg.jpeg" /></figure><h4>Comparing the Identity Uniqueness provided by Location Data with established Physical Biometric Signals.</h4><p><em>A technical paper by Roberto Colecchia, Rafael Gouveia, Filipe Martins, Hector Pinheiro, Matheus Leite and Raiza Oliveira.</em></p><p>At Incognia, we recently published a technical paper showing that the Identity Uniqueness based on user location history can be a very strong identity signal.</p><p>The accuracy that can be achieved using location behavior for Identity Uniqueness is higher than the FAR (False Acceptance Rate) of physical biometrics technologies in mobile consumer applications. Comparing methods, identity-based on location achieves an identity uniqueness between <strong>1: 1.1M</strong> and <strong>1: 17M</strong>, compared with a False Acceptance Rate (FAR) of established physical biometric signals between <strong>1: 50K</strong> to <strong>1: 1M</strong> for fingerprint or face authentication.</p><p>You can download the full paper at this link:</p><p><a href="https://www.incognia.com/hubfs/resources/using-location-as-a-signal-to-affirm-identity-online-incognia-paper.pdf">https://www.incognia.com/hubfs/resources/using-location-as-a-signal-to-affirm-identity-online-incognia-paper.pdf</a></p><p>To arrive at this result we have analyzed:</p><ul><li>User data available from academic studies</li><li>Public user data based on the U.S. Census</li><li>Incognia network data based on 200M+ Mobile Phones.</li></ul><p>At a high level, we have identified 2 key parameters that can help determine the identity of the user based on user location history.</p><p>1) <strong>Number of “Location Points”</strong> for each user: in our study, a “location” is a place that a user visits frequently and where he/she/they usually spends some time. So, for example, “Home” can be the user’s location #1, “Work” can be the user’s location #2, etc. The more location points that are available, the higher the accuracy for the Identity Uniqueness, enabling easier identification of one user versus another user.</p><p>2) <strong>Resolution of the “Location Unit”</strong>: some of the studies based on publicly available data were based on somewhat coarse location unit resolution e.g. Cell Tower Coverage Size (~10 Miles, ~16 Km radius) and Census Tract Area Size (~10–90 sq miles, ~25–230 Km2). Incognia leverages GPS, WiFi, and other signals based on the user’s smartphone sensors, so the location unit resolution is much higher. In this study, we have considered Incognia data based solely on GPS precision level (50m radius), to evaluate the accuracy. The higher the resolution of the location unit considered, the higher the accuracy for the Identity Uniqueness, enabling easier identification of one user from another.</p><p>To define the resolution of the “Location Unit” in this paper, we have used the geohash public domain geocode system. As a summary, in Table 1 are the key sizes for location units.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KARw74a9C-AWKSxWzCjBZg.jpeg" /></figure><p>We have defined as <strong>kₙ,ₘ</strong> the accuracy for the Identity Uniqueness obtained with <strong>n</strong> location points and geohash level = <strong>m</strong>.</p><p>In a couple of existing academic studies (referenced in the technical paper), we found some corresponding values, based on</p><ol><li>U.S. Census Tract Resolution (approximately geohash level 4: 39.1km x 19.5km) with 2 user locations (<strong>k₂,₄</strong>)</li><li>Mobile Network Cell Tower resolution (approximately geohash level 5: 4.9km x 4.9km) with 11 user locations (<strong>k₁₁,₅</strong> )</li></ol><p>The academic researchers have established the following accuracy:</p><ol><li><strong>k₂,₄</strong> = between <strong>1: 150M</strong> and <strong>1: 150K </strong>for different sets of US employed population</li><li><strong>k₁₁,₅</strong> = <strong>1 : 1.5M</strong></li></ol><p>In this novel paper, at Incognia we have investigated the accuracy of Identity Uniqueness based on the Incognia location database, determined by the following configurations:</p><p>● Number of location points<strong> n</strong> = 2, 3, 4, 5</p><p>● Location unit resolution = <strong>m</strong> = geohash level 7 (city block resolution, as highlighted in Table 2). Therefore, determining <strong>k₂,₇</strong>, <strong>k₃,₇</strong>, <strong>k₄,₇,</strong> and <strong>k₅,₇</strong></p><p>Based on the Incognia database and location collected using 200M+ users&#39; mobile phones’ GPS, we have calculated the following accuracy for Identity Uniqueness (as reported in Table 2):</p><ul><li>Accuracy with 2 locations and city block resolution - <strong>k₂,₇</strong> = <strong>1: 1.1M</strong></li><li>Accuracy with 3 locations and city block resolution - <strong>k₃,₇</strong> = <strong>1: 1.9M</strong></li><li>Accuracy with 4 locations and city block resolution - <strong>k₄,₇</strong> = <strong>1: 5M</strong></li><li>Accuracy with 5 locations and city block resolution - <strong>k₅,₇</strong> = <strong>1: 17M</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4lpGsQKlHmcoOlOD0DNmzg.jpeg" /></figure><p>Showing this in a diagram format, we can see that the Identity Uniqueness accuracy based on Incognia database <strong>k₂,₇</strong>, <strong>k₃,₇</strong>, <strong>k₄,₇</strong> and <strong>k₅,₇</strong> in Figure 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/0*9BtCQE7TTIra7Ef5" /></figure><p><strong>Figure 1:</strong> Accuracy of location for Identity Uniqueness based on number of location points for geohash = 7 (city block resolution)</p><p>Furthermore, based on this analysis, we considered a comparison between the accuracy obtained with Incognia location technology and the FAR of leading consumer-grade biometric technologies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/0*LB8jhafVyl6qPFp1" /></figure><p><strong>Figure 2: </strong>Location Identity Uniqueness Accuracy (<strong>k₂,₇,</strong> and <strong>k₅,₇</strong> with Incognia data) &amp; FAR for Leading Biometric Technologies</p><p>Figure 2 shows that with a suitable number of locations and with a high enough location unit resolution (based on GPS), the accuracy of Location for Identity Uniqueness is comparable to or higher than the False Acceptance Rate (FAR) for physical biometric technologies. In fact, the accuracy shown for 2,3,4,5 or more location points and geohash level 7 (City Block Size) varies between <strong>k₂,₇</strong> = <strong>1: 1.1M</strong> and <strong>k₅,₇</strong> = <strong>1: 17M</strong>. For the leading biometric technologies in consumer products — Apple and Microsoft, as reported in their web documentation — the FAR for fingerprint recognition (Touch ID and Windows Hello) is in the range of <strong>1: 50K</strong> while for face recognition (Face ID and Windows Hello) is in the range of <strong>1: 1M</strong>. By comparison, the odds of guessing a typical 4-digit passcode is <strong>1 in 10,000</strong>.</p><p>From the data collected, the reader can see that the location Identity Uniqueness Accuracy:</p><p>● increases with the number of the available location points</p><p>● increases with the resolution of the location unit.</p><p>Given these results, location technology with an appropriate number of location points and an appropriate resolution can be considered a valid and robust means to affirm identity for online consumer applications. The accuracy that can be achieved for the Identity Uniqueness is higher than the FAR (False Acceptance Rate) of physical biometrics technologies in mobile consumer applications.</p><p>From a privacy perspective: Incognia promotes the mission of developing high-performance technology without storage or access to data that can directly identify users since Incognia does not collect unique static identifiers from mobile devices, associated accounts, or civil identification data. Incognia follows the fundamental principles of Privacy by Design, has SOC 2 Type II Certification, and complies with LGPD (Brazilian Privacy Law), CCPA (California Privacy Law), and GDPR (European Union Privacy Regulation).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c01d35660a35" width="1" height="1" alt=""><hr><p><a href="https://medium.com/incognia-tech/using-location-as-a-signal-to-affirm-identity-online-c01d35660a35">Using Location as a Signal to Affirm Identity Online</a> was originally published in <a href="https://medium.com/incognia-tech">Incognia Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical Aspects of Machine Learning for Fraud Prevention in Production]]></title>
            <link>https://medium.com/incognia-tech/practical-aspects-of-machine-learning-for-fraud-prevention-in-production-1d4f96ef9320?source=rss----5b0cf5e0b18a---4</link>
            <guid isPermaLink="false">https://medium.com/p/1d4f96ef9320</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[fraud-detection]]></category>
            <category><![CDATA[incognia-tech]]></category>
            <category><![CDATA[lightgbm]]></category>
            <dc:creator><![CDATA[Vinícius Cousseau]]></dc:creator>
            <pubDate>Tue, 17 Aug 2021 12:12:53 GMT</pubDate>
            <atom:updated>2021-08-17T14:39:01.676Z</atom:updated>
            <content:encoded><![CDATA[<p>In addition to being a research field in constant evolution, Machine Learning (ML) is used today in several industrial applications, from <a href="https://cloud.google.com/vision">image classification</a> to <a href="https://eng.uber.com/uber-ai-blog-2019/?uclick_id=e8243d95-e2b1-4eb3-b245-b15a64a3a992">user mobility</a>. Incognia uses ML to help detect real-time authentication fraud attempts in mobile applications, thus reducing user’s friction. Using ML in production, however, brings forth some crucial challenges, from how to effectively choose the right model for the task at hand, to how to deploy and maintain it. This post highlights our key learnings about the process of developing and deploying an end-to-end ML pipeline from a practical standpoint, showing how we combined it with heuristics-based solutions to improve our risk assessment engine.</p><h3>Mobile Fraud detection — a brief introduction</h3><p>Mobile transactions are growing rapidly. The global mobile payments market, for instance, is projected to reach US$4.7 trillion by 2025. Concurrently, it is estimated that in 2019, 75% of all fraudulent transactions originated on mobile devices. Fraudulent events vary in type and perpetrators: account takeover (ATO), location spoofing, and SIM swap are a few examples. ATO fraud takes place when a fraudster gains full access to a legitimate user’s credentials and other information necessary for login and thus can perform actions without repercussion.</p><p>ATO prevention may be implemented in multiple stages of a user’s journey, the main one being at login. When solving this problem, there are two main challenges: detecting fraudulent login attempts and avoiding increasing friction for legitimate users. If all fraudulent login attempts are detected, but this leads to legitimate users having to verify every attempt through a secondary factor such as an email, this may harm the application by causing user churn due to an increase in friction. At the same time, accepting all logins without additional verification steps, while not detecting most fraud attempts, is undesirable. Thus, good ATO prevention solutions should strive to strike a balance between fraud detection and friction reduction.</p><h3>Challenges in ATO prevention</h3><p>Detecting fraudulent login attempts is a challenging task, and when using machine learning to tackle it, there are some key points to keep in mind:</p><ul><li>Most login attempts are legitimate, while fraudulent ones are rare. This means that data sets are expected to have a high-class imbalance factor, which makes the training and metric choosing processes trickier;</li><li>Success metrics vary from client to client and through time. Classifiers should be able to be easily tuned to either increase fraud detection at the cost of more friction or decrease fraud detection to reduce friction;</li><li>Labeled datasets are not widely available, and even if they were, features and class distribution vary wildly throughout different app user bases;</li><li>Login attempts are typically validated in a matter of a few seconds, at most. Thus, classifiers should be served through APIs with millisecond-level latency and be, in general, easy to deploy and maintain in production.</li></ul><h3>Training a classifier</h3><p>Given the challenges in obtaining and dealing with labeled datasets, one should consider whether to use unsupervised strategies, such as <a href="https://en.wikipedia.org/wiki/Isolation_forest">Isolation Forests</a>, or supervised ones, interpreting the problem as a binary classification. Since we had already developed successful <a href="https://developer.incognia.com/docs/br/v5/legacy/trusted-locations">Trusted Location heuristics</a>, using a supervised approach we wanted to leverage our domain knowledge and better understand the latent relationships between our features and fraudulent logins.</p><p><strong>Obtaining labeled datasets</strong></p><p>To obtain labeled datasets, we collected manually labeled data from clients that had been using our solution through a <a href="https://developer.incognia.com/docs/us/v6/apis/feedback-api">Feedback API</a>. For instance, if a login attempt was assessed as fraudulent by us, our client can send a request to our Feedback API indicating whether the end-user confirmed the fraud attempt (true positive) or denied it (false positive). This was the first challenge we overcame to use a supervised strategy.</p><p><strong>Adaptability</strong></p><p>The second challenge was choosing a classifier that could handle class imbalance, and be easily tuned, deployed, and maintained. We found all of that in <a href="https://lightgbm.readthedocs.io/en/latest/">LGBM</a>, which is a gradient boosting framework built on top of tree-based models. In addition to tree-based models being good alternatives to deal with class imbalance, LGBM also offers easy ways to choose different decision functions for them, which enables users to use state-of-the-art class-balanced functions such as <a href="https://arxiv.org/abs/1708.02002">Focal Loss</a> and <a href="https://arxiv.org/abs/1901.05555">the one published by Cui et. al</a>..</p><p>As for ease of use, LGBM provides a Python API and is easily integrated with Pandas and Sklearn. Its training is fast and can be distributed, it has native support for parallelization, and it has a low memory footprint, which we will show later on. We were also able to use different thresholds on top of the classifier score: one for fraud detection and another one for login approval, giving us a lot of room for tuning, as Equation 1 shows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*rjEv9t1d4KXDtWz8Hgo-aw.png" /><figcaption>Equation 1 — using two thresholds, α and β, on top of classification score S to approve or deny the transaction.</figcaption></figure><p><strong>Feature selection</strong></p><p>Having chosen the classifier, we now had to choose which features to use. This is where our accumulated knowledge about the fraud landscape gained through the lens of our heuristic approach helped us. We held a few brainstorming sessions and came up with several features which correlated to fraudulent logins and ATO in general. Then, we considered two means by which features would end up in production:</p><p><em>How important is this feature to the classifier’s output?</em> We utilized <a href="https://github.com/slundberg/shap">Shapley Additive Explanations</a> (SHAP), a game-theoretic approach to compute feature importance for machine learning models. When compared to <a href="https://scikit-learn.org/stable/auto_examples/ensemble/plot_forest_importances.html">standard feature importance computation methods</a>, SHAP offers clearer visual explanations and case-by-case analysis possibilities. We were then able to quickly identify and prune irrelevant features.</p><p><em>How easy it is to compute this feature in production?</em> We sketched architecture diagrams to understand the necessary workload for each remaining feature. Interestingly enough, we noticed that some of the most troublesome remaining features to compute in production were some of the least important in terms of SHAP. Those were also pruned.</p><h3>Deploying<strong> the classifier</strong></h3><p>To deploy the classifier, we had to deal with two different environments: training and production. In the training environment, we wanted to recurrently generate features in batch, train our classifier on top of those, and save the resulting model somewhere. Meanwhile, in the production one, we wanted to compute the features in real-time, feed them to the classifier to obtain a classification result, and use this result to compute a risk assessment to be returned to our clients. At this point, we had little machine learning infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*DfSDaz1jAD-Ngx_uUJ9OnA.png" /><figcaption>Figure 1 — our training and production ML architecture.</figcaption></figure><p><strong>Training architecture</strong></p><p>As Figure 1 shows, the training pipeline was implemented in two parts: feature generation and model training, both orchestrated with Rundeck. The feature generation makes use of Spark to compute the several classifier features in a distributed manner, using our data infrastructure. These features are then cataloged in our data lake and consumed in a separate, stand-alone training step written in Python, that trains the model, utilizes <a href="https://optuna.org/">Optuna</a> to optimize its hyper-parameters, and saves the classifier to specific S3 buckets.</p><p>We apply a black box analysis step during this training process, which is responsible for detecting potential issues with the newly trained model. For instance: if the success metrics vary too much from one run to another, this may indicate that a bug was introduced somewhere along the pipeline. Thus, committing this version of the classifier to production could cause some problems, and instead, we halt the process and notify the team.</p><p><strong>Production Architecture</strong></p><p>In production, we replicated the feature computation queries directly on top of our canonical user database. We performed several tests in staging and pre-production to assert equality between the results of those queries and the ones in the training pipeline. Then, we implemented a secondary API using the <a href="https://fastapi.tiangolo.com/">FastAPI</a> framework to process these features.</p><p>We chose FastAPI because it is easy to integrate with LGBM’s API, and because of its blazingly fast performance: our stress tests showed p99 latencies as low as 5 milliseconds and memory footprints, including the LGBM classifier loaded in memory with <a href="https://joblib.readthedocs.io/en/latest/">joblib</a>, of 300Mb. Latency was especially important to us due to a latency budget of 200 milliseconds for login risk assessments in our API.</p><p><strong>Heuristics first!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*br_2GeNgeQrsB4frhbEsVg.png" /><figcaption>Figure 2 — a sample of our API response.</figcaption></figure><p>Our API response consists of a risk assessment backed by a set of evidence. A crucial business choice for us is using the ML classification result as a piece of additional evidence, being complementary to our other heuristic evidence. Albeit powerful, ML approaches usually tend to gloss over the fact that some cases trivial to the human eye may not be well learned and thus receive an incorrect assessment.</p><p>There is also a great gap between training a classifier and understanding its results: in fact, there are whole research initiatives, such as SHAP, dedicated to understanding how a trained model works behind the curtains. Because of that, having safety nets composed of deterministic rules and even human-in-the-loop approaches helps keep solutions sane and safe.</p><h3>Closing thoughts</h3><p>In the course of 2 to 3 months, we were able to create and fully deploy a classifier with a <a href="https://www.incognia.com/resources/willbank-risk-based-authentication-for-account-takeover-reduction">measurable impact for our clients</a>: it increased our approval rate by 6 percentage points and our fraud detection rate by almost fifty percent. When combined with our other evidence, we were able to authenticate 93% of legitimate users without any additional friction and detect fraud with a false-positive rate of 0.0013%.</p><p>Our machine learning usage in production is still a work in progress, and we are constantly improving in this regard. We are currently gravitating towards <a href="https://mlflow.org/">MLFlow</a> as a better solution to organize our models. More importantly, this goes to show that simple, pragmatic solutions using ML responsibly can deliver great value. We hope we were able to highlight some key issues we found along the way and our solutions for them.</p><p>We have also developed other work related to ML in the past. Feel free to check some of our previous publications on topics such as <a href="https://link.springer.com/article/10.1007/s00521-021-05932-9">Place Deduplication</a> and <a href="https://pesquisa.bvsalud.org/global-literature-on-novel-coronavirus-2019-ncov/resource/pt/ppmedrxiv-20082172?lang=en">Social Distancing Analysis</a>. If any of this has piqued your interest and you want to take part in building a leading location-based zero-factor authentication solution, <a href="https://www.incognia.com/careers">Incognia is hiring</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d4f96ef9320" width="1" height="1" alt=""><hr><p><a href="https://medium.com/incognia-tech/practical-aspects-of-machine-learning-for-fraud-prevention-in-production-1d4f96ef9320">Practical Aspects of Machine Learning for Fraud Prevention in Production</a> was originally published in <a href="https://medium.com/incognia-tech">Incognia Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Challenges of running gRPC services in production (part 2)]]></title>
            <link>https://medium.com/incognia-tech/challenges-of-running-grpc-services-in-production-part-2-eb2d3b319e66?source=rss----5b0cf5e0b18a---4</link>
            <guid isPermaLink="false">https://medium.com/p/eb2d3b319e66</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[envoy-proxy]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[contour]]></category>
            <dc:creator><![CDATA[Rafael Acevedo]]></dc:creator>
            <pubDate>Tue, 20 Jul 2021 18:00:08 GMT</pubDate>
            <atom:updated>2021-07-21T17:09:09.742Z</atom:updated>
            <content:encoded><![CDATA[<p>Almost a year ago, I wrote about the <a href="https://medium.com/incognia-tech/challenges-of-running-grpc-services-in-production-b3a113df2542">challenges of running gRPC services in production</a> and how we handled them at Incognia (if you haven’t read it, I suggest you do, as this one will be based on it). Since then, the gRPC ecosystem has evolved quite a bit, ranging from new service discovery protocols to first-class support in proxies.</p><p>All this new tech allowed us to simplify the way we deploy gRPC services and how they communicate with each other while keeping everything reliable and high-performant (these are must-have features for Incognia, given that we handle requests from more than 100 million devices). The main topic of this post will be the evolution of our gRPC architecture over the last year.</p><h3>Load balancing</h3><p>A major issue when running gRPC in production is load balancing. This happens due to the persistent nature of connections (it uses HTTP/2). In the previous post, we showed how we were using Envoy together with external-dns (with AWS Route53) to make load balancing even across multiple server instances (in our case, Kubernetes pods).</p><p>While this approach worked nicely, it required some configuration in the server’s deployment to handle DNS cache TTL correctly and some additional security group configuration for communication between multiple Kubernetes clusters.</p><p>After some research, we found <a href="https://projectcontour.io/">Contour</a>, which is a kubernetes <a href="https://kubernetes.io/docs/concepts/services-networking/ingress-controllers/">ingress controller</a> that uses Envoy under the hood. We decided to test it, as we were already using Envoy directly and found no issues with it.</p><p>Basically, Contour listens for changes to Kubernetes Ingresses and updates the underlying envoy configuration accordingly, as the following diagram shows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/0*xDTqVT8bohkTlhCR" /></figure><h3>Deploying Contour</h3><p>While deploying Contour is quite straightforward, the recommended configuration is running Contour as <a href="https://kubernetes.io/docs/concepts/workloads/controllers/deployment/">deployment</a> and Envoy as <a href="https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/">daemonset</a> (running one envoy instance per Kubernetes node). This proved to be inefficient for our workload, as we need to scale Envoy up and down as the load changes during the day, independently of the Kubernetes nodes.</p><p>For example: if we have a Kubernetes cluster with 5 nodes, we would have to run 5 Envoy instances if they are deployed as a daemonset. If we run Envoy as a deployment, we scale Envoy using <a href="https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/">HPA</a>, enabling us to run fewer instances of Envoy when the request count is low and a higher number of pods when the request count is high.</p><h3>gRPC Connection Configuration</h3><p>To understand how we should configure gRPC connections on Envoy, let’s take a look at the whole flow, including DNS details.</p><p>We have 2 DNS entries: one for the gRPC server (my-api.mydomain.com) and one for contour ( contour.mydomain.com). contour.mydomain.com points to the Envoy pods using a <a href="https://kubernetes.io/docs/concepts/services-networking/service/#headless-services">headless service</a>, while my-api.mydomain.com is simply a CNAME to contour.mydomain.com. The flow is detailed in the following diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bLhGjkYGUVlYL8nI" /></figure><p>In the first step of the diagram, a gRPC client calls a gRPC method using my-api.mydomain.com as the DNS. It will resolve to one of the envoy’s pods, which will handle calls made through this connection. As the connection is persistent, a single pod would handle connections from this client, which is not ideal.</p><p>To avoid this, we set a <a href="https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/core/v3/protocol.proto.html#core-httpprotocoloptions">maximum connection duration</a> time between the client and envoy (currently this is set to 5 minutes, but it depends heavily on the use case). This forces the client to create a new connection to a new Envoy pod every now and then, allowing for better load balancing between the client and Envoy. Below are the configs used in contour.yaml.</p><pre>disablePermitInsecure: false<br>accesslog-format: envoy<br>timeouts:<br>  max-connection-duration: 5m<br>  connection-shutdown-grace-period: 15s<br>cluster:<br>  dns-lookup-family: v4</pre><p>In addition, for cases in which the number of client pods is low, we configure client-side load balancing between the client pod and envoy to avoid idle envoy pods. Below is an example of the configuration we use to create grpc-java’s BlockingStub:</p><pre>ManagedChannel channel =<br>    ManagedChannelBuilder.forAddress(host, port)<br>        .defaultLoadBalancingPolicy(&quot;round_robin&quot;)<br>        .intercept(clientInterceptors)<br>        .build();<br>channel.getState(true);//create connection on initialization<br>MyApiBlockingStub stub = MyApiGrpc.newBlockingStub(channel);</pre><p>In the second step of the diagram, the envoy pod chooses a pod that can handle the request forwards the gRPC call to it. Envoy is able to know which pods can handle the request via the DNS provided by the client (my-api.mydomain.com), which is the same as defined in the server’s ingress.</p><h3>Conclusion</h3><p>With this architecture, we simplified the approach we used previously, centralizing configuration (like gRPC connection timeout) in Contour/Envoy, so the clients become simpler while keeping the calls highly performant (in our tests, the envoy added about 0.3ms of overhead, which is negligible for most scenarios).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb2d3b319e66" width="1" height="1" alt=""><hr><p><a href="https://medium.com/incognia-tech/challenges-of-running-grpc-services-in-production-part-2-eb2d3b319e66">Challenges of running gRPC services in production (part 2)</a> was originally published in <a href="https://medium.com/incognia-tech">Incognia Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling (messy) address data]]></title>
            <link>https://medium.com/incognia-tech/handling-messy-address-data-4d51bbb7e8e3?source=rss----5b0cf5e0b18a---4</link>
            <guid isPermaLink="false">https://medium.com/p/4d51bbb7e8e3</guid>
            <category><![CDATA[string-matching]]></category>
            <category><![CDATA[fraud-detection]]></category>
            <category><![CDATA[address-verification]]></category>
            <dc:creator><![CDATA[Afonso Delgado]]></dc:creator>
            <pubDate>Thu, 03 Jun 2021 16:23:37 GMT</pubDate>
            <atom:updated>2021-06-07T17:49:31.457Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Bd0ttr3LGlDOl7oN.jpg" /></figure><blockquote>Thanks to <a href="https://medium.com/@vmrcousseau">Vinicius Cousseau</a> for contributing to this blog post.</blockquote><p>Matching addresses is an important problem in the fraud detection industry: we need to make sure that an address submitted by a user matches one from a reliable source (a government-related data source, for instance), in order to evaluate if the submitted address is consistent. Also, being able to consistently group generic address strings by their real meaning — the physical location which they represent — is important to avoid duplicated information and improve the quality of products built upon them.</p><p>Matching strings by themselves is already a difficult enough challenge for which there are many approaches available ranging from <a href="https://en.wikipedia.org/wiki/Record_linkage">machine-learning </a>to <a href="https://en.wikipedia.org/wiki/String_metric">purely algorithmic techniques</a>. On top of that, in our specific case, we also need the match to be as fast as possible, even allowing ourselves to sacrifice some correctness, if necessary.</p><p>However, when dealing with addresses, we bring up yet another level of complexity. Incognia’s API addresses can come as a single string, or as structured objects with hierarchical fields representing the various components of an address, like the city, street, and number, for example. Besides that, an address carries much more context-related information, which in turn can cause variance for addresses representing the same physical location. For example, we know that a string related to a street name may end with an abbreviation for the road name, as in “West 54th St.”, but could also come without it, as “West 54th Street”, or the number could come as a range, like “First Street, 2–5” in contrast with “First Street, 2”. So, we have to consider this and other kinds (and there are <a href="https://www.mjt.me.uk/posts/falsehoods-programmers-believe-about-addresses/">many</a>) of problem-specific information to improve the quality of our match, using this information to normalize the address strings.</p><p>That said, we begin to describe our approach to normalize and match address strings, in order to use them in our anti-fraud products. There is no better place to start than with our data.</p><h3>Our Data</h3><p>The main source of our address data is end-users. We receive address data from multiple companies, like fintech, digital banks, delivery apps, and many others. The range of industries makes our address data very irregular in terms of content since the way the addresses are collected from the users can change from company to company. The address data is however regular in terms of format since all companies adhere to the <a href="https://docs.incognia.com/apis/onboarding-api">Incognia’s API</a> format for addresses, that is an address line, normally separated by commas, or a structured object that looks like this:</p><pre>&quot;structured_address&quot;: {<br>    &quot;locale&quot;: &quot;en-US&quot;,<br>    &quot;country_name&quot;: &quot;United States&quot;,<br>    &quot;country_code&quot;: &quot;US&quot;,<br>    &quot;state&quot;: &quot;NY&quot;,<br>    &quot;city&quot;: &quot;New York&quot;,<br>    &quot;borough&quot;: &quot;Manhattan&quot;,<br>    &quot;neighborhood&quot;: &quot;Midtown&quot;,<br>    &quot;street&quot;: &quot;5th Av.&quot;,<br>    &quot;number&quot;: &quot;123&quot;,<br>    &quot;complements&quot; : &quot;2nd Floor&quot;,<br>    &quot;postal_code&quot;: &quot;10110-0001&quot;<br>  }</pre><p>We store the addresses in an encrypted manner, only to be decrypted by the services that will use them to derive the anti-fraud evidence based on an address match.</p><h3>Address Normalization</h3><p>To make the address strings comparable, we first must normalize them. However, this is not a fail-proof process, but, instead, a collection of steps that target direct and common modifications of address strings done by end-users and tries to revert those modifications to a single standard.</p><p>It is important to say that there are already some very useful libraries like <a href="https://github.com/openvenues/libpostal">libpostal</a> or <a href="https://github.com/datamade/usaddress">usaddress</a> that offer address normalization.</p><p>However, using these off-the-shelf tools may not solve each problem regarding normalization in real-world scenarios. As we’ve noted, our data comes from a great variety of sources and each of those can treat addresses in their own customized way, which can lead to different address content that may not be suitable to be used along with these libraries. Besides that, there is also the performance side of the problem, since, for example, libpostal requires almost 7GB of memory footprint to work with a non-trivial deployment process.</p><p>That is the reason at Incognia we are dealing with a more personalized solution: the only guide on how good our normalization is performing must be our data.</p><p>Let us get to it, then.</p><h4>Field separation</h4><p>The first step in the normalization stage is to separate the fields of an address. One way of doing that is to break the fields by some separator and use the <a href="https://www.immagic.com/eLibrary/ARCHIVES/TECH/OASIS/XAL_V2.PDF">XAL</a> format to represent the address. Here, we will keep it simpler, and just use the fields as they are submitted by the user. We assume that the user inputs an address in the following format</p><pre>{<br>  &quot;country&quot;: &quot;United States&quot;,<br>  &quot;state&quot;: &quot;NY&quot;,<br>  &quot;city&quot;: &quot;New York&quot;,<br>  &quot;borough&quot;: &quot;Manhattan&quot;,<br>  &quot;neighborhood&quot;: &quot;Midtown&quot;,<br>  &quot;street&quot;: &quot;5th Av.&quot;,<br>  &quot;number&quot;: &quot;123&quot;<br>}</pre><h4>Basic steps</h4><p>We first begin with some basic, well-known steps for normalizing the address. They are:</p><ul><li><strong>Lower case everything</strong>: we make sure that we are, in terms of comparing, only paying attention to which character we are comparing, instead of the case of it.</li><li><strong>Strip accents</strong>: accents are very common in languages other than English, like Portuguese, Spanish, French, German, and many others. The point here is to remove those accented characters since they compare differently to the striped ones. An example of that is “são paulo” which gets transformed to “sao paulo”.</li><li><strong>Remove punctuation, symbols, and meta-information</strong>: the next step is removing punctuation, symbols, and meta-information, mainly because some users tend to use them and some not. So, for example, we remove “.”, “,”, “-”, “state of” from fields (the last one only from the state field).</li></ul><p>Then, we get:</p><pre>{<br>  &quot;country&quot;: &quot;united states&quot;,<br>  &quot;state&quot;: &quot;ny&quot;,<br>  &quot;city&quot;: &quot;new york&quot;,<br>  &quot;borough&quot;: &quot;manhattan&quot;,<br>  &quot;neighborhood&quot;: &quot;midtown&quot;,<br>  &quot;street&quot;: &quot;5th av&quot;,<br>  &quot;number&quot;: &quot;123&quot;<br>}</pre><h4>Replace numbers and ordinals</h4><p>After the basic steps, we can proceed to replace the numbers, roman numerals, and ordinals in the fields by writing them out. For example, we want to transform “5th avenue” into “fifth avenue”.</p><p>The idea behind doing that is to achieve a better comparison or distance measure among those fields, as we can transform “5th avenue” into “6th avenue” by only changing a single character, whereas transforming “fifth avenue” into “sixth avenue” requires more changes, making them easier to tell apart.</p><p>We can also choose which fields to apply this transformation, since for the number field it is better to keep it as it is and parse it as an actual number, and, if needed, detect number ranges, like “Main St., 5–20”.</p><pre>{<br>  &quot;country&quot;: &quot;united states&quot;,<br>  &quot;state&quot;: &quot;ny&quot;,<br>  &quot;city&quot;: &quot;new york&quot;,<br>  &quot;borough&quot;: &quot;manhattan&quot;,<br>  &quot;neighborhood&quot;: &quot;midtown&quot;,<br>  &quot;street&quot;: &quot;fifth av.&quot;,<br>  &quot;number&quot;: &quot;123&quot;<br>}</pre><h4>Strip bracketed information</h4><p>Another useful transformation is to remove any text that is enclosed by brackets, parentheses, and the like. For example, transform “fifth avenue (next to Adidas shop)” into simply “fifth avenue”. The reason behind this is that some users tend to add this extra information in fields as a way of giving reference points to their addresses.</p><p>In our implementation, this is done by a simple regex match.</p><h4>Replace and remove common tokens</h4><p>This step is responsible for tackling common tokens related to the address fields. For example, for the street field, we may see tokens of the sort of “st”, “av”, “rd”, called abbreviations, that can be replaced by “street”, “avenue”, “road”, their expansions, and then we can even delete those expansions so that they cannot interfere with the comparison part of the match.</p><p>This also works for state abbreviations. We replace the abbreviations with the full state name in order to allow a fuzzy match in this field. For example, when we have two state fields being “ny” and “neew york”, it is better to transform the first one into “new york” and then compare instead of trying to convert the last one to the abbreviation.</p><p>We also remove prepositions and connectives like “of”, “and”, and “to” from the fields to perform better tokenization in the matching step.</p><p>The way by which this replacement is made is quite simple and standard (see the abbreviation expansion section on the <a href="https://www.mapzen.com/blog/inside-libpostal/">libpostal inner works post</a>): we use a dictionary that maps the abbreviation to the correspondent expansion, allowing even several abbreviations for a single expansion.</p><pre>{<br>  &quot;country&quot;: &quot;united states&quot;,<br>  &quot;state&quot;: &quot;new york&quot;,<br>  &quot;city&quot;: &quot;new york&quot;,<br>  &quot;borough&quot;: &quot;manhattan&quot;,<br>  &quot;neighborhood&quot;: &quot;midtown&quot;,<br>&quot;street&quot;: &quot;fifth&quot;,<br>&quot;number&quot;: &quot;123&quot;<br>}</pre><h3>String matching</h3><p>Once addresses are normalized, we need to be able to match them. We do this field by field in a hierarchical manner — we first match countries, then states, and so on — and for doing that we follow two steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*qeSYdqIGHTv984F-EsEd3A.png" /><figcaption>Hierarchical match</figcaption></figure><p>The first step is to break the fields into several tokens, splitting them by the space character. For example, “santa monica” becomes [“santa”, “monica”]. This is done so we can compare each token individually instead of the entire string.</p><p>After that, we calculate a measure of similarity between each token. In our implementation, this is done by using the Levenshtein distance, which can be seen as the minimum number of single-character edits necessary to turn one string into the other. We chose the Levenshtein distance as a distance measure to do it since it proved to be good enough to perform the match using our normalized data and has a great performance. However, other <a href="https://en.wikipedia.org/wiki/String_metric">string metrics</a> could be also used as well as ML-related approaches.</p><p>Once each token is compared with its correspondent, we accumulate the results and expose a final score of similarity to the comparison of that specific field, which can be used to assert if it is a match or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*QWMfhAA2VEGLm72Y4lTl7Q.png" /><figcaption>match</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*mGaNIdMa9l8Cekb-PPO0aw.png" /><figcaption>no match</figcaption></figure><h3>Iteration</h3><p>A final and continuous step to our address match is iteration.</p><p>Many factors can change the distribution, correctness, or performance of our matching pipeline, including the arrival of new companies in our client base, changes to current ones, and new product necessities, so we need to keep updated with that as well.</p><p>That is why we are constantly analyzing new data, looking at performance metrics, and cherry-picking failing cases in order to find weaknesses in our current strategy.</p><h3>Conclusion</h3><p>So, that is it! This was a brief review of how we perform normalization and match of addresses in our services.</p><p>We did not provide a full and thorough specification of our implementation here, mainly because, as we said, doing normalization and address match depends very much on the format of the address data, not only in terms of how it was created, but also by whom it was created — the end-users — since this data can vary across countries, regions, and even among different people.</p><p>We hope, however, to have contributed to a more general understanding of the things that we look for in an address to improve the quality of the final match, the basic forms of normalization, that are simple and fast, and the look of our address data pipeline.</p><p>Are you interested in building frictionless anti-fraud products with us? Check out our <a href="https://www.incognia.com/developers">developer portal</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d51bbb7e8e3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/incognia-tech/handling-messy-address-data-4d51bbb7e8e3">Handling (messy) address data</a> was originally published in <a href="https://medium.com/incognia-tech">Incognia Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[(message “Hello World!”)]]></title>
            <link>https://medium.com/incognia-tech/message-hello-world-54844e5fba34?source=rss----5b0cf5e0b18a---4</link>
            <guid isPermaLink="false">https://medium.com/p/54844e5fba34</guid>
            <category><![CDATA[incognia-tech]]></category>
            <category><![CDATA[incognia]]></category>
            <category><![CDATA[developer-edition]]></category>
            <dc:creator><![CDATA[Alan Gomes]]></dc:creator>
            <pubDate>Tue, 04 May 2021 13:02:54 GMT</pubDate>
            <atom:updated>2021-05-04T17:23:15.849Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tu0wOoQUFe7cnNy_hmQCzw.jpeg" /><figcaption><a href="https://www.flickr.com/photos/94778205@N00/1717425332">“Hello, World!”</a> by <a href="https://www.flickr.com/photos/94778205@N00">alternatePhotography</a> is licensed under <a href="https://creativecommons.org/licenses/by-nc-nd/2.0/?ref=ccsearch&amp;atype=rich">CC BY-NC-ND 2.0</a></figcaption></figure><p>Today is an exciting day for the Incognia engineering team as Incognia announces the release of its free Developer Edition.</p><p>We invite you to check out our <a href="https://hubs.li/H0MwJ-20">Developer Portal</a>, <a href="https://us.incognia.com/">documentation</a>, <a href="https://dash.incognia.com/api-reference">reference implementations</a>, and most importantly we encourage you to integrate and test the SDK and APIs (you just need to <a href="https://accounts.incognia.com/login#signup">signup here</a>).</p><p>Since launching Incognia’s location identity solution for mobile 10 months ago our SDK has been installed in millions of devices enabling fintech and m-commerce companies to fight back against fraud without adding friction to the user experience. Now with the Developer Edition, Incognia is making its SDK and APIs available free for any size company to leverage location behavior and device intelligence to detect fraudulent logins and transactions on their mobile apps.</p><p>The Developer Edition includes not only free use of the SDK and APIs but also a step-by-step integration wizard to make the installation super simple and also reference implementations.</p><p><strong>Why are we excited about this new Developer Edition?</strong></p><p>With the new Developer Edition of Incognia we are excited to be removing barriers for mobile app developers to get started. We have included thousands of free API requests with the free Developer Edition to enable any size company to launch and grow their mobile app with security built-in from day one.</p><p>We are looking forward to your feedback and thoughts on how to use location identity to build a frictionless authentication experience. (you just need to <a href="https://accounts.incognia.com/login#signup">signup here</a> and then you’re ready to go).</p><p><strong>What to expect next from Incognia?</strong></p><p>Over the next few weeks and months, we will be publishing details of the underlying technology used in the development of our solution. For many app developers, the use of location behavior and device intelligence is new. While our goal with the Developer Edition is to make your development job easier we also want to give you the background knowledge to understand the underlying design. We are planning to cover topics such as:</p><ul><li><strong>Challenges running a large scale service</strong></li><li><strong>Machine learning on production</strong></li><li><strong>Software engineering best-practices</strong></li><li><strong>How to fight mobile fraud</strong></li><li><strong>Location identity on practice</strong></li><li><strong>Privacy by design techniques</strong></li></ul><p>Please reach out with any and all feedback, and topics you would be interested in reading more about. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54844e5fba34" width="1" height="1" alt=""><hr><p><a href="https://medium.com/incognia-tech/message-hello-world-54844e5fba34">(message “Hello World!”)</a> was originally published in <a href="https://medium.com/incognia-tech">Incognia Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Privacy Friendly Histogram: the pros and cons of not knowing the user]]></title>
            <link>https://medium.com/incognia-tech/privacy-friendly-histogram-the-pros-and-cons-of-not-knowing-the-user-aca3feb7c7b3?source=rss----5b0cf5e0b18a---4</link>
            <guid isPermaLink="false">https://medium.com/p/aca3feb7c7b3</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[hyperloglog]]></category>
            <category><![CDATA[privacy-by-design]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[inloco-platform]]></category>
            <dc:creator><![CDATA[Afonso Delgado]]></dc:creator>
            <pubDate>Tue, 04 May 2021 00:51:53 GMT</pubDate>
            <atom:updated>2021-05-04T00:51:53.909Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oN93TK8w56fbf9RynSPZsA.jpeg" /><figcaption>Source: <a href="https://towardsdatascience.com/set-theory-basic-notation-da93c3d48090">https://towardsdatascience.com/set-theory-basic-notation-da93c3d48090</a></figcaption></figure><p>Gathering intelligence from data is one of the main byproducts of our technological era. However, it may come with the price of dealing with sensible data from the user.</p><p>Some simple and handy examples of such intelligence are frequency histograms. For example, suppose you are a business owner and want to know the level of recurrence of your customers, i.e., how many times does a customer come to your business in a week. An effective way to display such information is to create a histogram of customers’ visits as shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*61qtzVwv9bHmXo5PLnjFwQ.png" /><figcaption>The process of computing a frequency histogram. The histogram represents the information of how many customers went to the place a determined number of times.</figcaption></figure><p>Computing these histograms from large amounts of data requires a lot of computational power and memory. We need to keep track of a lot of entries to compare and aggregate. Also, from the point of view of privacy, we may encounter a problem, since we need some kind of identifier of the entries.</p><p>We’ve come up with a simple but effective idea to perform such task both in a fast and privacy-friendly way. But first, let’s talk about a keystone in such idea: <strong>HyperLogLog</strong>.</p><h3>The HyperLogLog</h3><p>HyperLogLog (or HLL for the close friends) is a probabilistic data structure introduced by the french computer scientist Phillipe Flajolet. The idea of such a structure is to efficiently gather information about a set (a collection of things). With it, we can compute the cardinality (number of things without repetition) of the set and perform unions with other HyperLogLogs.</p><p>For example, suppose that you plan to go to some of your friend’s house and play games. You have a pretty large set (in the order of millions) of games, your friend also have a lot of them and you two will play together. Since, of course, the plan was to play all the games you both had, you want to know previously how many unique games you both together have, so you could allocate the right time to arrive at your friend’s house and still be able to play it all before you need to go (since you have to be at home in time for dinner). HyperLogLog can save you some time in this process. It is just a matter of building the structures of each of your sets, so the cardinality estimation of the union of your sets of games is almost instantaneous!</p><p>Because of these properties, this structure can be (and is) used for tracking large sets of data. However, another useful and perhaps accidental property is that it makes data pseudo-anonymous. In the process of creating the structure, elements are converted to the number of leading zeros in the binary representation of their hashes, and only the maximum value of those are saved. Therefore,it is not easy (and a lot of times not even possible) to backtrack those elements.</p><p>However, the intuition behind doing this is not simple, so an example helps a lot. The following example is totally derived from the <a href="https://odino.org/my-favorite-data-structure-hyperloglog/">blog post</a> of Alessandro Nadalin (and figures totally inspired in <a href="https://xkcd.com/">xkcd</a>, check it!).</p><h3>LogLogParty</h3><p>Imagine that you were invited to the great<em> </em><strong><em>LogLogParty</em></strong>. There is a rule: if you meet someone new, you must ask their phone number. So you, trying to keep track of how many new people you met, decide to think of strategies to do so. You come up with a list:</p><h3>First Strategy: just write down the names</h3><p>The first strategy is pretty straight-forward, you just need to keep a list of all the people (or phone numbers of people) you met, remove duplicates (assuming you met so many people that actually “met” some twice by mistake) and bam: you have your new friends count.</p><p>The problem with such an approach is that you are going to have a lot of headache if you meet too many people. Removing duplicates and counting becomes a pain in the ass.</p><h3>Second Strategy: count the number of leading zeros</h3><p>The second strategy is a little more intelligent when it comes to making a lot of new friends. You, instead of keeping track of all the names of all the new people you have met, decided to count the number of leading zeros in each person’s phone number and only save the largest you’ve seen! At first look, this strategy seems terrible. However, let’s think about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*7qAg21TeDMpdtcMZ0n4myg.png" /></figure><p>If you met someone who has five leading zeros in their phone number, this is an event so unlikely that you must have met, on average, 100.000 people (assuming the erroneous but useful hypothesis that phone numbers are uniformly distributed and do not depend on the person who possesses it). So that’s the new way to count: just keep track of the maximum number of leading zeros you got, and, at the end of the party, compute 10 to the power of this number.</p><p>Of course, the problems with this method arise immediately: you can only count in powers of ten, and, worse, you can be (un)lucky that, in your first new friend, you met someone with, let’s say, six leading zeros and automatically have 1 million more friends, instead of one.</p><p>I mean, if you were an assiduous partier, in the average, you would count the right number of friends!</p><h3>Third Strategy: making the second strategy better</h3><p>The problems with the second strategy involved poor precision and high variance of the result. Well, there is a simple way to solve that (and it was spoiled in the very second strategy): do it a lot of times!</p><p>But keep calm! You do not need to attend a lot of parties. Just change a little part of your strategy. Instead of keeping track of a single number of zeros, let’s keep track of the number of zeroes in each bucket! A bucket is a recipient that contains phone numbers that have some kind of similarity. For example, we could have buckets representing the number on the left of the phone number. So numbers starting with 9 belong to bucket 9, and so on. Thinking this way, when you meet someone new, the first thing to do is go to their bucket. There, you keep track of the maximum number of leading zeros in the rest of the number (excluding the bucket part). For such, you now have a lot of buckets, each one containing the maximum number of leading zeros of a number that you’ve seen that belongs to that bucket.</p><p>The good side in this strategy is that it takes away a great part of the luck factor, since you would have been very lucky to be lucky in each of the buckets. And also provides a new batch of possible values for cardinality, since we are going to take the average of the counting in each bucket.</p><h3>Your new friend: HyperLogLog</h3><p>You were just introduced to <a href="http://www.dragonwins.com/domains/getteched/bbc/literature/Bloom70.pdf">HyperLogLog</a>. Swap people for elements, phone numbers for hashes, calculate some fancy mathematical bias correction, and you can count cardinalities of large sets, with low memory and processing, with the cost of a little bit of imprecision. Of course, this example fails to comprehend all the components of HyperLogLog. There is a lot of work in both technical and academic perspectives to make it better and more precise.</p><h3>What about the histograms?</h3><p>As I said, we developed a way of computing those histograms that we talked about. The idea is to use HyperLogLogs (kinda) to do so.</p><p>The idea behind the strategy is that the number of leading zeros in a hash, the value that we track in an HLL, can be very representative of a single element. Let’s say an element has ten leading zeros in its binary representation’s hash, and this is such a rare event (given a reasonable number of users) that we can almost for sure say that if we see ten leading zeros, it, almost certainly, is that element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qJkcq-qUIPvqWGMcJe6xpw.png" /></figure><p>So, the number of leading zeros is a quasi-ID of a user, and the buckets act like a subsampling of all population. Why not do the histogram of the leading zeros? That’s precisely it.</p><p>Imagine that we have computed HLLs for each day of the week. If we look in a specific bucket in day one and see six leading zeros saved and look in day two and see the same six leading zeros count, it’s probably the same person (could have been just luck and were two different people, but this is unlikely). So we know that this person has come to this place on two separate days. Therefore, we compute how many times we see some number leading zeros for each bucket on the entire week and voilà: histogram without knowing the user!</p><p>An important factor that we need to take in consideration is that the histograms outputted by the algorithm are normalized, since looking at the maximum number of leading zeros is equivalent to sub sampling the population. However, going back to the real histogram is just a question of multiplying each of its entries by the population size, that can be estimated with the very HyperLogLogs.</p><h3>Actually not that simple</h3><p>In theory, the strategy is excellent, in practice, not so good (mostly because I lied in the theoretical part). Assuming that the number of leading zeros in a bucket uniquely defines a user is valid for the majority of cases, but not all, and such cases are not negligible. Precisely those cases where this is not true make the histogram look skewed. The figure below shows it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*_Ym_R0IA4JsW5fHin8A0PQ.png" /><figcaption>These are two histograms based on the same data (50.000 elements with frequency uniformly distributed in 10 days in a span of a month). The blue one is calculated with the exact method and the orange is calculated as described with HLL (with precision of 10). The orange histogram is skewed to the right.</figcaption></figure><h3>The solution: MinCodeSample</h3><p>Since we could not compute, with precision, the histograms associated with a HyperLogLog set, a new approach was taken: to save a part of the hash of the user with the maximum number of leading zeroes. In such a way, it’s possible to avoid collision with (a lot) more probability. Being able to avoid collision implies that computing the histogram is simply a matter of randomly subsampling the population, and, that, statistics guarantees!</p><p><strong>MinCodeSample</strong> does it. Its structure is exactly like HyperLogLog, except that it saves part of the hashes in each bucket (in fact, there is a structure just like this called <a href="https://arxiv.org/pdf/1710.08436.pdf">HyperMinHash</a>, although not used for histograms). In this way, we can achieve a lot more precision, with the cost of saving part of the information that identifies a single user, that is, with the cost of less privacy. This trade-off comes from the fact that, the longer the part of the hash that we save, the easier it becomes to identify the user that generated that hash. At the same time, the better and more precise the histogram calculation becomes, since we become even more sure of the uniqueness of this sample.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*OWI7uPUsFIeIb5DSYLJ9Jg.png" /><figcaption>The same data as in the previous figure. Blue is the exact computation, and orange is the estimation based on MinCodeSample (saving the full hash of elements). The results are a lot more similar.</figcaption></figure><h3>Conclusion</h3><p>Although we are aware that <a href="https://arxiv.org/pdf/1808.05879.pdf">cardinality estimators do not preserve privacy</a>, we understand that the MinCodeSample represents a step towards keeping our user’s data safer. This safety comes from the fact that:</p><ul><li>Users’ ID are hashed with salt.</li><li>Only the users with the maximum number of leading zeros on the hash representation in each bucket are (possibly) traceable.</li><li>Raw data is not used to perform computations.</li></ul><p>Therefore, we see this structure with kind eyes and we are eager to improve it. Maybe you can help us.</p><h3>Are you interested?</h3><p>If you are interested in building context-aware products using a powerful location technology that genuinely cares about user’s privacy, then check out our <a href="https://jobs.kenoby.com/inlocoglobal">opportunities</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aca3feb7c7b3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/incognia-tech/privacy-friendly-histogram-the-pros-and-cons-of-not-knowing-the-user-aca3feb7c7b3">Privacy Friendly Histogram: the pros and cons of not knowing the user</a> was originally published in <a href="https://medium.com/incognia-tech">Incognia Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving Data Consistency Issues in Our Places Platform]]></title>
            <link>https://medium.com/incognia-tech/solving-data-consistency-issues-in-our-places-platform-f3942a96a072?source=rss----5b0cf5e0b18a---4</link>
            <guid isPermaLink="false">https://medium.com/p/f3942a96a072</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[inloco-platform]]></category>
            <dc:creator><![CDATA[Vinícius Cousseau]]></dc:creator>
            <pubDate>Tue, 12 Jan 2021 22:15:41 GMT</pubDate>
            <atom:updated>2021-01-12T22:15:41.324Z</atom:updated>
            <content:encoded><![CDATA[<p>Location data is one of the core drivers of the work we do at Incognia. It provides us with a way to infer contextual information in the real world, which can in turn be used to <a href="https://medium.com/inlocotech/modelling-viruss-spread-based-on-geolocation-data-b2e2c439ead6">model the spreading of a virus</a> or build <a href="https://medium.com/inlocotech/a-small-peek-inside-in-locos-location-platform-a7e95b7b4e94">engagement solutions</a>.</p><p>However, as rich as the location data might be, many other applications require more information on what a pair of latitude and longitude coordinates might represent: is this location inside a bar? What is the street address pertaining to this location? What’s near there after all?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/0*YpPwq18Mc6zXgAl7" /><figcaption>Figure 1 — There’s much more information beyond latitude and longitude pairs!</figcaption></figure><p>In order to provide this kind of information, we built a database of Place entities, also commonly referred to as Points of Interest (POIs) in scientific literature. The planning of our places infrastructure began when our products were still at their infancy, and at the time we realized that:</p><ul><li>We needed an in-house places database, since paying for 3rd-party API usages would not scale well and we would not be able to enrich and validate the data ourselves;</li><li>Good coverage and reliable information were mandatory. Additionally, every place must’ve had at least latitude and longitude coordinates and a name;</li><li>We needed this infrastructure to behave like a platform, and, as we expected all other teams to become internal clients, data should be available in a fast and easy way.</li></ul><p>This article firstly describes our platform as of the beginning of Q1 2019, and expounds<strong> data consistency issues</strong> we found during the years. We also present our current solutions for these issues, and how we’re planning to improve them.</p><blockquote><em>For ease of understanding, we define a place entity for this article as follows:</em></blockquote><blockquote>A place entity is a direct representation of a physical location in the real world which has well-defined boundaries, a purpose, a considerable size, and is both atemporal and a source of context.</blockquote><blockquote><em>Thus, it is useful to think that, in our database, places are most often either public sites or establishments. This definitions excludes, for instance, building floors, stretches of sand on a beach, and landmarks with negligible boundaries, e.g. a statue.</em></blockquote><h3>Foundation: an Event-sourced Architecture</h3><p>With these goals in mind, we set out to develop what would become an event based platform which dealt with place records’ ingestion from both the Web and internal sources, exposed them by APIs and web interfaces, and was processed on a daily basis by several Spark distributed applications. All the while, it provided full visibility of what was going on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MLLPMmmkKtx96Yl3" /><figcaption>Figure 2 — Our Places architecture circa Q1 2019</figcaption></figure><p>To arrive at this architecture, we went through several iterations which gave us golden learning opportunities. While these are not the focus of this blog post, we highly encourage taking a look at one of our <a href="https://s3-sa-east-1.amazonaws.com/thedevconf/presentations/TDC2019REC/arquitetdados/TCV-4533_2019-10-12T010056_[AD]%20Apresenta%C3%A7%C3%A3o%20TDC%20Recife.pdf">previous presentations</a> about the topic.</p><p>As Figure 2 depicts, all data we ingested from the web was being sent to Apache Kafka. Additionally, users were able to manipulate our places database by utilizing our web interface (Places Web). Every action in our DB thus boiled down to a set of INSERT, UPDATE, DELETE or MERGE Kafka records, sent to the <em>places-db-commit-log</em> and then processed by our DB Writer service.</p><p>Let’s say, for instance, that we ingested a new place entity called <em>Shopping Plaza</em>: if we already had a place entity representing this real-world place in our DB, we would just UPDATE its information, since its phone number, address, timetable, or other attributes could have changed. If, however, there was no equivalent place entity in the DB, we would just INSERT it. Similarly, manual user operations executed through our web interface would generate operations pertaining to the aforementioned set.</p><p>By using Incognia’s Kafka structure we also gained, with little to no effort, automatic backup of every action issued to our db. However, we still needed a way to visualize those actions in real time for debugging and analysis. In order to do that, we utilized Incognia’s <a href="https://github.com/inloco/kafka-elasticsearch-injector/">Kafka Elasticsearch Injector</a>, publishing every action event in a dedicated Elasticsearch cluster with Kibana.</p><p>Another important aspect of our architecture was the usage of three different data sources. First of all, we note that our PostgreSQL DB was and still remains our canonical data storage. Furthermore, while it may seem odd to do that, we found out that our clients required certain query types for which there were better tools.</p><p>For full text queries, for example, Elasticsearch offers a full range of query operators and optimizations which we would have to implement by hand with PostgreSQL, and would generate code that is hard to maintain, hard to improve, and very error-prone.</p><p>Similarly, Redis proved to be an amazing tool for simple and efficient in-memory key-value queries, including our main use case of geospatial queries which are gracefully performed by the <a href="https://redis.io/commands/georadius">GEORADIUS</a> operator.</p><p>All in all, we learned that <em>there is no silver bullet when it comes to picking a database to deal with complex records</em> such as places, which will be used by multifaceted applications. Each one will have pros and cons, and it is up to the developer to choose how to combine them to best suit their needs.</p><p>Finally, our architecture was also able to handle large-scale batch processing of our whole dataset by distributed algorithms and machine learning models. Subsequently, we were able to explore and iterate quickly over solutions for problems found in our data.</p><h3>Consistency Issues</h3><p>After some time using this architecture, we started noticing a few issues. One of the most important ones was that all <strong>synchronization</strong> between our three data sources was being done programmatically by us, which led to several inconsistencies between the databases.</p><p>Just like that, by ingesting a lot of data from different sources, we began to have several data quality issues. For instance: we mentioned that whilst receiving a new record, we needed to check whether or not it was already present in the database. As it turns out, this problem is far from easy, and is in fact touched upon by different scientific research areas, such as <a href="https://en.wikipedia.org/wiki/Record_linkage">Entity Resolution/Record Linkage</a>.</p><p>Meanwhile, as we started to acquire more knowledge in dealing with places data, we noticed that almost all of the issues approached by us were complex enough to deserve their own blog post.</p><p>Summing them up, we highlight:</p><ul><li>Places deduplication/matching;</li><li>Synchronization between data sources;</li><li>Categorization of Places (detecting if a given place is a restaurant, a supermarket, etc.);</li><li>Detecting chain stores;</li><li>Enriching and normalizing address data;</li><li>Detecting hierarchy between places;</li><li>Generating Place entities through other data, such as movement patterns.</li></ul><p>Along the years, we have gained significant experience in dealing with all the aforementioned architectural and data issues, but more so in the <strong>DB synchronization</strong> and <strong>places deduplication</strong> tasks.</p><p>These tasks are inherently connected, since both of them affect our data consistency, that is: the former deals with consistency among different data sources, while the latter deals with consistency in a single data source. Thus, we go deeper into these two problems and how we dealt with them.</p><h4>Synchronizing Different Databases</h4><p>Suppose that you are performing queries in two different endpoints of a single API, one of them providing full text search, and another one providing geospatial queries. Among the first query’s results, you receive a record with an id A, which has latitude and longitude coordinates of &lt;-8.0631229, -34.8717757&gt;. Then, you query the geospatial endpoint, looking for places in a 100 meter radius from these exact coordinates, but record A is nowhere to be seen.</p><p>Frustrating, isn’t it? This was one of the synchronization issues that was happening in our Places API. By manually replicating INSERT, UPDATE, DELETE, and MERGE actions in our DB Writer, a failure in executing the given action in one of the DBs and a success in the other ones meant that we were leaving our DBs with inconsistent states.</p><p>In order to fix that, we could attempt to roll back each successful operation if another DB resulted in a failure, but these rollback operations in turn could fail as well. Basically, it is hard to perform queries in a transactional behavior for three different databases simultaneously.</p><p>It was at that time that we read about the Change Data Capture (CDC) pattern, and <a href="https://debezium.io/">Debezium</a>. A <a href="https://medium.com/inlocotech/ensuring-data-consistency-across-services-with-the-transactional-outbox-pattern-90be4d735cb0">recent post</a> in our blog already mentioned Debezium and the CDC pattern at depth, but in short, Debezium is able to read every change being applied to a database (in our case, PostgreSQL) and stream it to Kafka in an event sourced format, similar to our <em>places-db-commit-log</em>.</p><p>By consuming these records, one would be able to not only reconstruct a previous state of the database, but also replicate them elsewhere, which, fortunately, was just our use case. Hence, we configured and started using Debezium to stream data from our canonical PostgreSQL data storage, and made use of <a href="https://docs.confluent.io/current/connect/index.html">Kafka sink connectors</a> to read the data and write to our Elasticsearch and Redis databases. Figure 3 displays our debezium integration.</p><blockquote><em>While Confluent has a public </em><a href="https://docs.confluent.io/current/connect/kafka-connect-elasticsearch/index.html"><em>Elasticsearch sink connector</em></a><em> available, we had to create the Redis sink ourselves, since no market solution seemed to handle both record deletions and geospatial data as well as we’d hoped. We intend to make this project public in the future.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/0*Lq7RpjMmV1NAOMpv" /><figcaption>Figure 3 — Debezium integration with Elasticsearch and Redis connector sinks.</figcaption></figure><p>By modifying this part of our architecture, we consolidated PostgreSQL as our canonical data storage, and provided eventual consistency to all our other DBs.</p><p>Having eventual consistency means that eventually all queries for a specific record will return the same value, and, in our case, <em>eventually</em> boiled down to latencies upwards of tens of milliseconds during normal operation. Also, we were able to get rid of a great chunk of code in our DB Writer, which led to the service being much easier to maintain and less error-prone.</p><h4>Places Deduplication</h4><p>Deduplicating places is probably the hardest of the issues we’ve faced, and whose resolution would be most relevant to our company. Since we consume data from different sources, including the web (which is, to put it mildly, noisy), it is common for us to receive Place entities representing the same real world Place over and over again.</p><p>As mentioned in our architecture, we need not only to solve this problem in an online fashion, but also via batch processing of our data.</p><p>We define the problem of Places deduplication as such:</p><p><em>Given a set of place entities, how do we detect if they represent the same real-world place?</em></p><p>Which, in turn, can be relaxed to:</p><p><em>Given a pair of place entities, how do we detect if they represent the same real-world place?</em></p><p>Our first attempts to solve this problem were very domain-specific and manual, but resulted in an unacceptable rate of false positive and false negatives. Thus, we also started to explore machine learning approaches for this issue, backed up by other researches in the area of Record Linkage/Entity Resolution that tended to go this way [1, 2].</p><p>Subsequently, our current deduplication pipeline in production makes use of distributed computation to partition data and generate potential duplicate place pairs, and then sends each pair to a model which discerns between pairs indicating duplicate places (positive) and pairs indicating non-duplicate places (negative). This model was first trained as a Random Forest on top of pairwise place features, and then adapted to the <a href="https://lightgbm.readthedocs.io/en/latest/">LGBM</a> framework in order to reduce memory footprint for online usage.</p><p>The binary output, which solves the relaxed version of the problem, can then be brought back to the original statement by representing each place as a node in a graph in which edges connecting two arbitrary places indicate that they are duplicates. Detecting the connected components of this said graph gives us the end result we are looking for.</p><p>As Figure 4 shows, we reached an end-to end solution for the problem, with our classification model generating both batch results and being exposed via APIs for real-time queries.</p><p>By offering APIs for our solution, we were able to improve real-time detection of duplicate places, preventing data inconsistencies before they even happened in the database itself. At the same time, our model reached a normalized <a href="https://en.wikipedia.org/wiki/Gini_coefficient">gini coefficient</a> of <strong>0.92</strong> on top of our ground truth, and ended up being published as a scientific paper [3].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/0*4RlPAAVMP5nHnyTk" /><figcaption>Figure 4 — Place deduplication pipeline, using a Random Forest as the classification model.</figcaption></figure><p>We were not fully satisfied with the results, however, and following successful reports of deep learning usage to solve matching problems in other domains, we decided to explore that field.</p><p>This resulted in a new solution which is well on its way to replace the classification method shown in Figure 4 by a deep neural network architecture that aims to generate word level, character level, geographical level, and category level embedded representations of places and compare them to generate a binary output, akin to Figure 5. Although not being in production yet, this new method was already able to outperform our previous one in several metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*12rw8xRYR2MsFfjoPLq_6Q.jpeg" /><figcaption>Figure 5 — A simplified view of our deep neural network for duplicate places classification.</figcaption></figure><p>Another key takeaway we had during exploration of this issue was that including human feedback in the deduplication loop is crucial, since deduplication is a hard task and not even the best algorithms will get everything right. This coincided with the creation of an internal Places QA team, and a shift in our focus to make direct user-made operations have the highest possible priority in our DB, even over our models.</p><p>We attempted to improve that by creating a Places Playground, where place pairs for which our models are not so sure are sent to undergo a voting process. Positive pairs are then consolidated in our DB, and help us improve our ground truth set. Figure 6 displays a sample pair being taken up to be voted on in the Places Playground.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vCFhT0j1oJVEn-Jx" /><figcaption>Figure 6 — A sample place pair up for voting in our Places Playground. Notice that this case was hard for our model due to slight differences in addresses and lat lngs, which may point to different stores of a chain inside the same mall.</figcaption></figure><h3>Our Architecture Today</h3><p>Since we only touched upon a few core issues that we tackled during the latest months, Figure 7 displays only part of our full architecture, omitting some new services and flows that would subtract readability from this post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gTrTV53oiUuCM4Lx" /><figcaption>Figure 7 — Our current architecture, with some services filtered out.</figcaption></figure><h3>Closing Remarks</h3><p>In this post, we described a past state of our places data platform in an architectural and data level, and touched upon some of the core issues we had to tackle, while providing some of the key learnings we had. We hope this article is of use to anyone exploring Places data or building a data platform.</p><h3>References</h3><p>[1] Santos, R., Murrieta-Flores, P., Calado, P., and Martins, B. (2018). Toponym Matching through Deep Neural Networks. International Journal of Geographical Information Science, 32(2).</p><p>[2] Yang, C., Hoang, D. H., Mikolov, T., &amp; Han, J. (2019). Place Deduplication with Embeddings. The World Wide Web Conference on — WWW ’19. The World Wide Web Conference. <a href="https://doi.org/10.1145/3308558.3313456">https://doi.org/10.1145/3308558.3313456</a></p><p>[3] Cousseau, V., Barbosa, L. (2019). Large-scale Record Linkage of Web-based Place Entities. In Proceedings of the 34th Brazilian Symposium on Databases. <a href="https://sol.sbc.org.br/index.php/sbbd/article/view/8820">https://sol.sbc.org.br/index.php/sbbd/article/view/8820</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3942a96a072" width="1" height="1" alt=""><hr><p><a href="https://medium.com/incognia-tech/solving-data-consistency-issues-in-our-places-platform-f3942a96a072">Solving Data Consistency Issues in Our Places Platform</a> was originally published in <a href="https://medium.com/incognia-tech">Incognia Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visits variations analysis from the visits detection capability perspective]]></title>
            <link>https://medium.com/incognia-tech/visits-variations-analysis-from-the-visits-detection-capability-perspective-4325bbc70560?source=rss----5b0cf5e0b18a---4</link>
            <guid isPermaLink="false">https://medium.com/p/4325bbc70560</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[inloco-platform]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Hector Pinheiro]]></dc:creator>
            <pubDate>Tue, 12 Jan 2021 13:44:16 GMT</pubDate>
            <atom:updated>2021-01-12T13:44:16.471Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MoY-oQgK9b0tV1K5EfRhoQ.png" /></figure><p>The detection of visits that occurred in a specific place is on the core of In Loco’s technology, and our teams are continuously working to improve the detection capability, which refers to the ability to detect visits whenever they occur. The task is performed on mobile devices using partner applications that use our SDK (Software Development Kit).</p><p>Anonymous data are collected not just to detect visits but also for posterior extraction of contextual information associated with them (as the place and the intention of the visitor). Since there are several restrictions on data collection routines imposed by operating systems and several concerns about device resources (such as power consumption), the improvement of detection capability is not an easy task and demands the development of intelligent algorithms that identify the best moments to collect relevant data.</p><p>Our detection capability is profoundly impacted by the number of mobile application partners and by our algorithms (that are executed within them). Updates on our SDK or the availability of new partners affect the number of observed visits in our database directly, causing variations that make it difficult to compare in different time periods. This way, an essential step in the analysis is to estimate the influence caused by the variation of the detection capability.</p><h4>Note</h4><blockquote>As <strong>Medium</strong> does not support math expressions naturally in the text, most of them will be cited with regular alphabet letters rather than the expression itself.</blockquote><p>For a particular location, given two different time periods <em>i</em> and <em>j,</em> and the number of visits observed on them (<em>Vi </em>and <em>Vj)</em>, the relationship between them can be expressed as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*gzD135n8t40tFpG-ht5k_A.jpeg" /></figure><p>where <em>Cij</em> defines the visits variation coefficient between the time periods.</p><p>Table 1 presents the visits and variation coefficients observed in São Paulo for different months. One can notice the increase in visits amount from Aug 2017 to Oct 2017. A variation coefficient of 1.86 was observed in Sep 2017, which represents a 86% increase in the visits amount. Although any clustering algorithm can perform this step, it is natural to believe that most of it was caused by the <strong>ability to detect more visits</strong>.</p><p>Here, we describe our approach to estimate the influence of our visits detection capability on the variation coefficients. It consists of proper modelling the visits variation coefficients and decomposing them into components with specific variation causes. By identifying which parts are impacted by changes in the detection capability, we may use estimations of these components and remove them from the observed visits variations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*Wcb7wvV-350d5HqWACUeww.jpeg" /><figcaption>Table 1 — Visits and variation coefficients observed in São Paulo (Brazil) for different time periods. The variation coefficients are computed by comparing the visit amount with the previous month.</figcaption></figure><h4>Variation coefficients modeling</h4><p>The detection capability relates the number of observed visits and the number of visits that actually happened. For a given place and time period, <em>i</em>, the number of observed visits are</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*4FCZ94LRcOmH9ENlFDCnuA.jpeg" /></figure><p>where <em>V^i</em> is the actual number of visits and <em>Deti </em>is the visits detection capability, which can be seen as the proportion of actual visits that is observed by our technology. Furthermore, given the detection capabilities in two different time periods, we may define their relationship as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*TKgXdm2--rKZzYPmareLMA.jpeg" /></figure><p>where <em>Cdetij</em> defines a variation coefficient between them.</p><p>Although it is difficult to define the detection capability itself, the estimation of its variation through time is more feasible. Our goal here is to model the variations observed in places to estimate the variations of the actual visits, removing their effect in the detection capability.</p><p>Combining Equations 1–3,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*g2n9rbwF7lZpeUi4lznS7g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*O2TNpH8ICMSV3XS3bKwS_A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*vMqZQ_27VO7Cib4FfE7ltA.jpeg" /></figure><p>By defining,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*WVDl3AAseCkFLiUwD7Zj5Q.jpeg" /></figure><p>we define a variation coefficient that relates to the estimation of the actual visits occurred in a given place in two different time periods. The next step relies on the estimation of <em>Cdetij</em>. Observe that the estimation of the variations in detection capability defines an estimation for visits variations, but not for the visits amount — it would only be possible if the actual visits were defined in at least one time period (Equation 6).</p><p>Depending on the changes that may occur in our visits detection capability, different impacts are observed in the number of observed visits. For instance, the increase of partner applications increases the number of devices producing visits while improvements in our detection algorithms may increase the number of visits observed for each device. Taking these aspects into account, we may define the visits observed in a time period <em>i</em> as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*HKHTjnCl82lliGRVGerSzQ.jpeg" /></figure><p>where <em>Di</em> is the number of devices that produced visits and <em>Ri</em> is the ratio between the number of visits and the number of devices. Similarly, the actual visits are defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*dI87NNi13nSel_4mtB9K3A.jpeg" /></figure><p>Combining Equations 2, 8 and 9, we can decompose the detection capability into two different components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*L0oJtKKwUBAf-vVreZiMUw.jpeg" /></figure><p>where <em>DetDi</em> defines the proportion devices that are observed and <em>DetRi</em> defines the proportion of visits that are observed for each device. Furthermore, the detection capability variation can also be decomposed into these components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*C0tS_rCtvc3AewzqhshzpQ.jpeg" /></figure><p>and the estimation of the analysis of the detection capability can be performed by estimating the D and R components.</p><h4>Estimation of variation coefficients</h4><p>It is not possible to estimate the detection variability in a particular place by observing its visits alone. Fortunately, variations in the detection capability cause a global effect in the visits variations, which allows us to estimate <em>Cdetij</em> of a specific place using the variations observed in other regions.</p><p>However, the effect caused by detection capability variations may vary significantly from to region to region. Therefore, it is necessary to estimate the variations for different areas and combine them in the estimation for a particular place.</p><h4>Regions of influence</h4><p>The basic idea of our approach is to estimate the detection capability components of the visits variations of a place (or region) — referred as “origin” — based on the so-called “regions of influence”. These geographic regions are chosen based on their influence on the visits that occurred in the origin region. The variations observed in the regions of influence are combined to estimate the variations components of the origin. This way, we use the global effect of the detection capability variations to estimate the local influence of these variations.</p><p>We will now describe our approach to find the regions of influence of a certain origin and how we can define weights for them, that can be used to combine their variations taking into account their importance in the observed variations. Figure 1 presents a diagram of our approach.</p><p>The first step consists in identifying the devices that visited the origin region in the period of analysis. These devices are then tracked, and all their visits are used to define the regions of influence. The assumption here is that only the regions visited by origin’s visitors would strongly influence future visits to the origin region.</p><p>The regions of influence are then defined by the spatial clustering of the visits’ locations. This step can be performed by any clustering algorithm. A simple way of achieving this is to convert the geographic coordinates of the visits to geohashes with appropriate precisions. This approach performs a geohash aggregation of the locations. In our tests, we used geohashes with 6-byte precision, which produce rectangular regions with dimensions of approximately 1.2km by 0.6km. To simplify the analysis, regions with low visit counts were not considered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*X5nQfAwb_w5sOL0bj5sp3A.png" /><figcaption>Figure 1 — Diagram of the visits variation coefficients estimation of an origin region.</figcaption></figure><p>Once fixed the regions of influence of a given place, we may associate each of them to a weight that is proportional to their importance. Here we considered an important region as a region that is frequented by many visitors from the origin.</p><p>For each region of influence <em>RIi</em> of a given origin, <em>RI={RI1, RI2, …, RIn}</em>, a weight <em>i</em> is computed and associated with it and then normalized to sum one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*NFB3nWdGonI8ZvvunF4Neg.jpeg" /></figure><p>Given the number of an origin’s visitors, <em>Ki</em>, that also visited the region of influence <em>RIi</em>, the associated weight is defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*peOzYhu8c07saJJ1ck5_uA.jpeg" /></figure><p>Figure 2 shows the regions of influence for two different origins located in São Paulo. Observe that the number of regions of influence can vary dramatically depending on the origin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*uiOYnA1Y_wIvZXxlBqMzgA.png" /><figcaption>Figure 2 — Regions of influence for two different origins located in São Paulo (Brazil). This image was generated using Uber’s <a href="https://kepler.gl/">Kepler</a> geospatial analysis tool.</figcaption></figure><h4>Coefficients combination</h4><p>As the detection capability variation of the origin is estimated by combining the variations estimated in the regions of influence, we need first to define <em>Cdetij</em> for each one of them. We could define the estimation of <em>Cdetij</em> by computing the visits variation on the region. However, as mentioned before, depending on the changes that occur in our detection capacity, different aspects of the variation may change. As expressed in Equation 11, the visits variation may occur from the difference on the detection of different devices, or from the variation on the visits produced by each device. For this reason, a better estimation for <em>Cdetij</em> is defined by the estimation of <em>Cdet,Dij</em> and <em>Cdet,Rij</em> independently.</p><p>Given the number of devices observed in different time periods <em>i</em> and <em>j</em>, <em>Di</em> and <em>Dj</em>, the variation on the device detection capability can be defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*MNPG_Qdpe4Irbl-ia_TvvQ.jpeg" /></figure><p>Similarly, given the observed ratios between the number of visits and the number of devices, <em>Ri</em> and <em>Rj</em>, the variation on the visits and devices ratio is defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*QgGDx05dRzxnvKiZ_5aI-A.jpeg" /></figure><p>Then, for each origins’ region of influence, <em>RIk</em>, 1 ≤ k ≤ N, its estimated detection capability variation, <em>Cdet,kij</em>, is defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*yrKOEw2C_DvRSxDnrfZ_-w.jpeg" /></figure><p>Finally, we can define the origins’ detection variation as the linear combination of the variations estimated for the regions of influence using their weights:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*RYVG1ncDZ4Xb6iIVXh5UGA.jpeg" /></figure><p>Observe that by using the weights to combine the detections variations, we assign the participation of the region of influence in the estimated value according to its importance for the visits that occur at the origin.</p><p>In this modeling, the combination of detection capability variations of the regions of influence is the same as the combination of theirs visits variations. Combining Equations 14, 15 and 17:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*eMqy5isbdF8UdyInfLsUzw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*q5Ic50liqjMumfnEDhXkOw.jpeg" /></figure><p>where <em>Vki</em> and <em>Vkj</em> are the visits observed in the region of influence <em>k</em>, in times <em>i</em> and <em>j</em>, respectively.</p><p>Equation 19 requires visits to be observed in all the regions of influence in time <em>i</em>. Since these regions are possibly not fixed and may change over time, we must define a modeling that is well defined for the case where no observed visits occur in time<em> i</em>. For this reason, instead of directly combining the visits variations of the regions of influence, we may combine the visits observed in times <em>i</em> and <em>j</em> and then compute the variation observed in the combined visits:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*pT6O5npnVPKSVj1VdFi88Q.jpeg" /></figure><p>As presented by Equation 7, the estimated variation coefficient can be used to normalize the variation observed in the visits of a specific place. Instead of trying to estimate the capacity itself, the normalized coefficient can be used to analyze the variations observed in the visits regardless of the detection capacity variations. This kind of analysis removes the variation effects of changes occurred in the visits detection process, allowing a more accurate analysis of the observed flow in places and regions.</p><p>In order to validate the proposed normalization method, we used reliable data about people’s flow in some commercial places. These data were provided by partners who are able to perform accurate measurements of the visits occurred in their facilities. The visits variations observed on these data were used as ground truth.</p><p>Figure 3 presents an example of the comparison between the standard and normalized variations measures observed in a place and the correspondent ground truth. The variations were defined on a daily basis by computing the visits variations compared to a fixed initial date (as in Table 1). In this case, the initial date was fixed at 04/02/2018 (first Monday of April).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*YnkH5vGdne1KVREq4h2gUQ.png" /><figcaption>Figure 3 — Example of normalization of the visits observed in a certain place.</figcaption></figure><p>Note that an increase in visits was observed at the end of July (black curve). Similarly to the data presented in Table 1, this increase in the visits numbers comes from the increase in the visits detection capability. This is evidenced by the variations observed in the ground truth (blue curve), which did not show this behavior.</p><p>The normalization method is able to correct this by removing the detection capability variations components of the observed visits. The resulting normalized variations (red curve) are close to the ground truth, <strong>showing that the flow behavior was preserved regardless of the detection capability variation.</strong></p><h4>Are you interested?</h4><p>If you are interested in building context-aware products through location, check out our <a href="http://inloco.com.br/carreiras">career</a> page. Also, we’d love to hear from you. Leave a comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4325bbc70560" width="1" height="1" alt=""><hr><p><a href="https://medium.com/incognia-tech/visits-variations-analysis-from-the-visits-detection-capability-perspective-4325bbc70560">Visits variations analysis from the visits detection capability perspective</a> was originally published in <a href="https://medium.com/incognia-tech">Incognia Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android app startup time: why we care]]></title>
            <link>https://medium.com/incognia-tech/android-app-startup-time-why-we-care-b70eada84b26?source=rss----5b0cf5e0b18a---4</link>
            <guid isPermaLink="false">https://medium.com/p/b70eada84b26</guid>
            <category><![CDATA[android-studio]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[incognia-tech]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Pedro Atanásio]]></dc:creator>
            <pubDate>Tue, 12 Jan 2021 13:03:10 GMT</pubDate>
            <atom:updated>2021-01-12T15:59:52.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_9sfjL1W97gNTdMVbAh_hw.jpeg" /></figure><p>When we talk about mobile applications, performance is a fundamental concept. The low resource availability in these types of devices means that any inefficient solution, no matter how small, is reflected in poor user experience, whether through a non-responsive UI or excessive battery consumption.</p><p>As if that wasn’t bad enough, <a href="https://developer.android.com/topic/performance/vitals">Android Vitals</a> performance metrics are used for app ranking on Google Play searches: apps with healthy metrics tend to appear first while apps that have bad performance are shown last. You can find more details <a href="https://developer.android.com/distribute/best-practices/develop/android-vitals">here</a>.</p><p>The Incognia SDK is embedded into hundreds of applications. It means that many companies and developers trust us to allow our code to run in their apps. That’s a big responsibility, and that’s why performance is so important to us.</p><h3><strong>Application startup performance</strong></h3><p>The first impression the user has from an application is the time it takes to start. Apps that take too long to show something useful may frustrate users, leading to bad reviews and uninstalls. It’s no accident that startup time is one of the Android Vitals metrics. This is also a relevant metric to us because our SDK is initialized whenever the application is started. It’s defined as the time it takes to show an activity since the user triggered the action of opening the app.</p><h3><strong>The cold start</strong></h3><p>Depending on the state of the application when the startup process is initiated, some additional effort may be needed to make the app operational. The scenario that is more time consuming and causes the most overhead is a cold start. The application needs to be launched from scratch, which is the case when the app launches for the first time since the device was booted or since the system killed the app. This is the worst case scenario, and it is when the startup delay can be more noticeable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*cMkvY68C3JIY7J41" /><figcaption><em>Application startup steps</em></figcaption></figure><p>In this scenario, the system first launches the app and shows a blank window until the startup process is completed. Then, it creates the main app process, which is responsible for creating the <em>Application</em> object and launching the first activity. When some parts of the app are already in memory, the startup process is simplified. These scenarios are known as hot/warm startups. For example, the app can be brought to the foreground if all of the activities are still in memory. In this case, the <em>Application</em> object has already been created, and the startup is faster.</p><h3><strong>The Application.onCreate() method</strong></h3><p>The system does most of the heavy lifting, but if you have overridden the <em>Application.onCreate()</em> method on your app, any code written here is going to be executed as part of the initialization process. It is a very handy place to write initialization logic since this method is called before any activity is created and thus before any user interaction. It is no coincidence that lots of libraries and SDKs recommend their initializations to be made in the <em>Application.onCreate()</em>. The result is that we end up with something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*ItTnBo7Rt85TV9U9" /><figcaption><em>Libraries being initialized on the Application.onCreate() method</em></figcaption></figure><p>The problem is that every single piece of code executed at this stage counts towards a bigger startup delay. The Incognia SDK also has to be initialized here, which explains why we are so obsessed with optimizing initialization time.</p><h3><strong>How much is too much?</strong></h3><p>Android Vitals considers a cold startup time to be excessively long when it takes five or more seconds to execute. In extreme scenarios, long-running operations that are part of the initialization logic may also cause <em>ANRs</em>. An <em>ANR</em> (Application Not Responding) event occurs when the UI thread is busy, and the app is unable to respond to user inputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/0*F9dgj80QYPuRnzac" /><figcaption><em>ANRs events on the Google Play Console</em></figcaption></figure><p>You can check the startup time data for your app in the Android Vitals section of the Google Play Console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Tcqb0az-9Keb1B0i" /><figcaption><em>Startup time data reported on Android Vitals</em></figcaption></figure><h3><strong>Diagnosis</strong></h3><p>The key to reducing startup time is to find the <strong>bottlenecks</strong> in the initialization process. Sometimes it is not trivial to find the culprit(s) just by looking at the code, but some patterns and tools may help you find them. Keep in mind that we are looking for synchronous operations that take a long time to execute, such as:</p><ul><li>Network operations</li><li>Disk operations</li><li>Heavy calculations</li><li>Synchronization problems (deadlocks)</li></ul><p>You should avoid doing these things synchronously on the main thread. Since the <em>Application.onCreate()</em> is executed on the main thread, any of those operations become initialization bottlenecks if not dispatched to the background.</p><h3><strong>Tools</strong></h3><p>The <strong>Android Profiler</strong> and the <strong>StrictMode</strong> are both tools that can help us to identify the sources of slowness. Something interesting about those tools is that they can show slow operations even on third-party code. This is especially useful when we suspect that one of those libraries that we are using is causing the issue.</p><h4><strong>Android Profiler</strong></h4><p>Android Profiler is a powerful tool introduced in Android Studio 3.0 that replaces Android Monitor. It gives the developer a detailed view of CPU, memory, and network usage of the app.</p><p>It allows us to verify which parts of the code are adding extra time to the startup process. Using the <strong>method tracing</strong>, it is possible to see which methods are taking too long to execute and what they are doing. This is not only useful to find problems in our code, but also to determine if any 3rd party library is poorly optimized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/0*Fgk26f1ceOPnrIoj" /><figcaption><em>Application.onCreate() execution time showed in the method tracing view</em></figcaption></figure><p>In the image above we have an example of what the method tracing in the Android Profiler can provide us. We can see that the <em>Application.onCreate() </em>of this sample application takes 2.92 seconds to execute. That’s under 5 seconds, but let’s try to understand what is happening. If we look closely, we’ll see that there are two library initializations calls in this method: <em>RemoteConfigLibrary.init() </em>and <em>AnalyticsLibrary.init().</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/0*b-C1Dm5rJyGe1EeV" /><figcaption><em>RemoteConfigLibrary.init() and AnalyticsLibrary.init() shown in the method tracing view</em></figcaption></figure><p>We can see that as part of its initialization process, <em>RemoteConfigLibrary</em> makes a synchronous network request. We were lucky that the initialization of this library only took 1.17s because depending on network conditions this request could have taken much longer! This is not good!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/0*BOM4NwQlNm7rVfA1" /><figcaption><em>Synchronous HTTP request on the main thread revealed by the method tracing</em></figcaption></figure><p>We can also see that the AnalyticsLibrary writes to the SharedPreferences as part of its initialization process. This is usually not a problem if the SharedPreferences is used for a small amount of data. This does not seem to be the case, and this is taking almost half the time of the method call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/0*eS7lXVZOAgtcpd5c" /><figcaption><em>SharedPreferences access on the main thread revealed by method tracing</em></figcaption></figure><p>Cool, isn’t it? The Android Profiler gives us the power to look under the hood to find hidden performance issues!</p><h4><strong>StrictMode</strong></h4><p>StrictMode is another tool that helps us find hidden performance problems. It works by warning the developer of undesired patterns such as network and disk operations on the main thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f7JQAR4q0Pe7Ex9U" /><figcaption><em>StrictMode initialization</em></figcaption></figure><p>The app used in the previous example crashes when running with the settings above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Csv5vlN9lwidDkRnXY24w.png" /><figcaption>The crash caused by StrictMode</figcaption></figure><p>Let’s check Logcat to find out the cause:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gjCQ_U2st5LQoYyK" /><figcaption><em>Stacktrace of the crash caused by StrictMode</em></figcaption></figure><p>We can see that the app crashes intentionally because <em>RemoteConfigLibrary.init() </em>makes a network call on the main thread. In this example, we configured StrictMode to crash our app if any anti-pattern is found, but there are less severe options such as warning dialogs and logs. You can find the full StrictMode documentation and options <a href="https://developer.android.com/reference/android/os/StrictMode">here</a>.</p><h3><strong>Fixing the issues</strong></h3><p>Discovering the source of the problem is a good start, but we need to fix the issues. There are a few things that you can do to offload the initialization:</p><ul><li><strong>Move the blocking code to a background thread: </strong>network and disk operations should not be executed synchronously on the main thread, especially during the application startup.</li><li><strong>Use lazy initialization:</strong> parts of your application don’t need to be initialized during startup. Try to identify those parts and delay the initialization as much as possible — e.g., the user profile might only be necessary on the profile activity and not very useful during startup.</li><li><strong>Dispatch 3rd party libraries initialization to a background thread:</strong> lots of library initializations on the Application.onCreate() will undoubtedly make it slower. Try to find the libraries that can be asynchronously initialized and move their initialization to a background thread.</li><li><strong>Remove defective 3rd party libraries:</strong> this is an extreme scenario, but if a specific library is too slow to be initialized and there is no possibility to initialize it elsewhere, you should consider removing it or replacing it with something better.</li><li><strong>Solve synchronization issues:</strong> The startup time might be increased if the main thread is blocked waiting for another operation executed on another thread. Try to find those locks.</li><li><strong>Avoid reflection:</strong> Reflection operations are known to be slow. Try to avoid a large number of them as part of the initialization. We were able to considerably improve the startup time of our SDK only by avoiding reflection. Reflection operations are very common in serialization libraries like Gson and Jackson.</li></ul><p>Other things can affect how long your app takes to start, but fixing those common issues is certainly going to give your app a speed boost. Your users will be happier and more engaged while you enjoy all those 5-star reviews!</p><h3>Are you interested?</h3><p>If you are interested in building context-aware products through location, check out our <a href="https://inloco.com.br/en/careers">opportunities</a>. Also, we’d love to hear from you! Leave a comment and let us know what you would like us to talk about in the upcoming posts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b70eada84b26" width="1" height="1" alt=""><hr><p><a href="https://medium.com/incognia-tech/android-app-startup-time-why-we-care-b70eada84b26">Android app startup time: why we care</a> was originally published in <a href="https://medium.com/incognia-tech">Incognia Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How we implemented the Incognia API Gateway]]></title>
            <link>https://medium.com/incognia-tech/how-we-implemented-inloco-platforms-api-gateway-ef6f4ac020af?source=rss----5b0cf5e0b18a---4</link>
            <guid isPermaLink="false">https://medium.com/p/ef6f4ac020af</guid>
            <category><![CDATA[gloo]]></category>
            <category><![CDATA[application-load-balancer]]></category>
            <category><![CDATA[envoy]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[api-gateway]]></category>
            <dc:creator><![CDATA[Lucas Barros]]></dc:creator>
            <pubDate>Tue, 12 Jan 2021 13:02:05 GMT</pubDate>
            <atom:updated>2021-05-03T20:27:57.997Z</atom:updated>
            <content:encoded><![CDATA[<p>At Incognia, our product engineering team takes advantage of a microservice-based architecture and therefore develops dozens of APIs that collectively compose our <a href="http://dash.inloco.ai/">Incognia Platform</a>. Every time someone accesses our platform, what they see is the result of numerous requests directed to those different APIs, each responsible for a specific piece of information.</p><p>For this to be feasible, we implemented an architectural pattern called API Gateway, and in this article, we are going to talk a little bit about this pattern and our journey to achieve the ideal API Gateway solution to our case.</p><h3>API Gateway</h3><p>This architectural pattern consists of a component that acts as a single entryway to your services: every single request passes through it and then is routed to the correct service.</p><p>In the context of microservices, an API gateway provides all of your services with a common set of features, such as authentication and observability, while abstracting away details that don’t need to be visible to your clients, such as the location of each service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v_ZNyns10KDTbRiTATL3tQ.jpeg" /><figcaption>Generic API Gateway</figcaption></figure><h3>Our first API Gateway implementation</h3><p>Back in 2019, we decided to do our first API Gateway implementation with two components that were widely used and that our team had some prior experience with <strong>AWS’</strong> <strong>Application Load Balancer (ALB)</strong> and <strong>Nginx</strong>.</p><p>ALB was valuable for providing both authentication and TLS termination. We were able to implement authentication simply by using ALB’s Open ID Connect capabilities, <a href="https://www.slideshare.net/AmazonWebServices/alb-user-authentication-identity-management-at-scale-with-netflix-net204-aws-reinvent-2018">as presented in AWS re:invent 2018 by Netflix</a>.</p><p>Nginx was required to proxy requests to our frontend and backend servers (that were spread across different Kubernetes clusters) and to make request header transformations (remove, add, and edit headers to requests).</p><p>There were many problems with this approach, and some of them were deeply related to Nginx operational processes, like observability and integration, which will be explained in more detail in the next sections. Furthermore, in our configuration, Nginx presented some annoying IP cache problems.</p><p>Besides that, ALB’s authentication also presented some operational and security issues, like <a href="https://auth0.com/docs/sessions-and-cookies/cookies#stateless-cookies">ALB session cookies being stateless</a>, making it difficult to revoke a session, and logout not invalidating the user’s session (cookie still valid after logout).</p><p>Given these pain points, we decided to spend some time researching the best alternatives for delivering a secure and flexible authentication approach that had a more high-performant and maintainable proxy solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3V4yO-iTpQFUcUYRXCELPQ.jpeg" /><figcaption>Our first implementation of Incognia Platform’s API Gateway</figcaption></figure><h3>Improving our first solution</h3><p>Let’s take a look at how we replaced ALB and Nginx and how it affected our system.</p><h3>Replacing Nginx</h3><p>As we searched through popular proxies in the market (HAProxy, Envoy, Traefik) to replace Nginx, Envoy caught our attention. We liked that it is <a href="https://medium.com/@mattklein123/optimizing-impact-why-i-will-not-start-an-envoy-platform-company-8904286658cb">not owned by any commercial entity</a> and at the time, other services were using it with great results, so leveraging it again would enable us to build more expertise on it.</p><p>Let’s take a look at how Envoy helped us solve some of the pain points Nginx presented.</p><p><strong>Observability</strong></p><p>Envoy exposes thousands of metrics in Prometheus format on the /stats/prometheus endpoint. It was a huge difference from our default Nginx monitoring, which exposed only <a href="http://nginx.org/en/docs/http/ngx_http_stub_status_module.html#stub_status">7 metrics</a>.</p><p>By using Envoy, we were able to monitor each request and response properties (latency, status_code, etc) per each service, something crucial to an API Gateway’s observability.</p><p>Envoy also provides an <a href="https://www.envoyproxy.io/docs/envoy/latest/operations/admin">Admin API</a> with valuable endpoints. By calling /logging?level=debug we were able to get more log information about proxied requests and responses and this was vital to investigating some route to service mapping errors we had during the implementation of this new solution.</p><p><strong>Integration</strong></p><p>Envoy’s configuration can be either static or dynamic, the latter by using <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/operations/dynamic_configuration">gRPC/REST-based APIs that provide configurations, collectively known as xDS</a>. As we have complex proxy settings and an ephemeral environment (Kubernetes), the dynamic configuration would be very handy and also a huge integration improvement from our default static Nginx configuration.</p><p>Additionally, by using dynamic configuration, we would be able to avoid unpleasant things like <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/operations/hot_restart#:~:text=Ease%20of%20operation%20is%20one,configuration">hot restart</a> or disruption to traffic when updating Envoy’s configuration. That said, the best alternative for us at the time was to use open source solutions that could help us get started developing with Envoy’s xDS.</p><p>That’s where we found <a href="https://docs.solo.io/gloo/latest">Gloo</a>. Gloo is a “control plane” for Envoy (which is a data plane) or simply a component that provides us plug and play xDS APIs and <a href="https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/">Custom Resource Definitions (CRDs)</a> for our Kubernetes environment, allowing us to define and update Envoy’s configuration in a very simple and more readable manner.</p><blockquote><strong>Gloo vs Ambassador</strong></blockquote><blockquote>Before deciding to use Gloo, we had to decide between Gloo and <a href="https://www.getambassador.io/">Ambassador</a>, another famous control plane for Envoy and Kubernetes. We chose Gloo because <a href="https://www.solo.io/blog/why-the-control-plane-matters/">it is more secure given that the control plane is separated from the data plane</a>.</blockquote><h3>Replacing ALB</h3><p>Envoy provides a filter called <a href="https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/ext_authz_filter">External Authorization</a>. For each request, Envoy consults this filter to check if the request is authorized, and if it’s not, it is denied with a 403 (Forbidden) response.</p><p>It’s possible to configure this filter for authentication purposes. By using this functionality, we were able to ditch our old ALB authentication solution and develop our own external authorization filter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*itaNjhFdAHAkpJNu4-DFzg.jpeg" /><figcaption>Envoy’s external authorization filter</figcaption></figure><p>This gave us more control over users’ sessions, the security problems we had with ALB (stateless session cookies and logout cookies not being invalidated) were no longer a problem. Furthermore, as authentication configuration became much more flexible, we were able to get rid of some of ALB’s limitations, including the inability to maintain a single session across subdomains and to individually choose which route to authenticate.</p><p>Nevertheless, our current API Gateway still has an ALB but it is for the purpose of enabling TLS termination. In the future, we plan to pass this responsibility on to Envoy as well.</p><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*gDATybvweAHGW1LnaG21ZQ.jpeg" /><figcaption>Our current Incognia Platform’s API Gateway solution</figcaption></figure><p>The need for an API Gateway to make our microservice architecture viable led us to start implementing it with AWS’ Application Load Balancer and Nginx, which did the job for a long time but presented many problems and limitations. By using Envoy and Gloo as an API Gateway, we were able to implement a solution that made our system more robust and secure. We also managed to increase observability and improve our integration process, as Gloo made it easy to use Envoy’s xDS, ideal for an API Gateway placed on a Kubernetes ephemeral environment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef6f4ac020af" width="1" height="1" alt=""><hr><p><a href="https://medium.com/incognia-tech/how-we-implemented-inloco-platforms-api-gateway-ef6f4ac020af">How we implemented the Incognia API Gateway</a> was originally published in <a href="https://medium.com/incognia-tech">Incognia Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>