<?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[Fitbit Tech Blog - Medium]]></title>
        <description><![CDATA[Fitbit — Engineering  Fitness - Medium]]></description>
        <link>https://medium.com/fitbit-tech-blog?source=rss----71d55fdd6fe---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Fitbit Tech Blog - Medium</title>
            <link>https://medium.com/fitbit-tech-blog?source=rss----71d55fdd6fe---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 15:31:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/fitbit-tech-blog" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Keep it Simple and SMART (KiSS) — Engineering Fitness]]></title>
            <link>https://medium.com/fitbit-tech-blog/keep-it-simple-and-smart-kiss-engineering-fitness-1269814dd03f?source=rss----71d55fdd6fe---4</link>
            <guid isPermaLink="false">https://medium.com/p/1269814dd03f</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[fitbit]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[self-service]]></category>
            <dc:creator><![CDATA[Jared Fuchs]]></dc:creator>
            <pubDate>Wed, 26 Aug 2020 15:07:45 GMT</pubDate>
            <atom:updated>2020-08-26T15:07:45.163Z</atom:updated>
            <content:encoded><![CDATA[<h3>Keep it Simple and SMART (KiSS) — Engineering Fitness</h3><p><strong>Authors:</strong> Jared Fuchs, Melody Spencer, Sukhendu Chakraborty</p><h3>Introduction:</h3><p>As part of the e-commerce and tools team at Fitbit one of our missions is to enable other teams by providing an extensible framework for surfacing device/application data to whoever needs it. Towards that goal, we have provided a common set of APIs that any team can implement that gives internal clients an easy way to view the status of a system or feature. This data is then exposed in easy to use internal tools supported by this framework.</p><h3>Motivation:</h3><p>Fitbit is a fast paced company with the mission to make the world a healthier place. As part of this goal, it is paramount that we as teams are efficient and self-sufficient to enable our users with critical information about their health and well being. The Core Tools team aims to make business processes efficient by providing the correct amount of information in a most effective and intuitive fashion to the data consumers within the organization. To achieve these objectives our team has conceptualized and implemented a generic SMART API framework to empower teams to expose information they own to the consumers that would like to use it. The name is inspired by <a href="https://en.wikipedia.org/wiki/S.M.A.R.T.">Self-Monitoring, Analysis and Reporting Technology</a>, a tool used for surfacing the health of hard drives in computers. At its simplest, the SMART API framework defines a standardized set of HTTP APIs designed to expose the right amount of information at the right level of detail.</p><h3>UI Design:</h3><p>We have come up with a generic UI design which is robust enough to accommodate the data visibility needs for various product teams like Heart rate monitoring, Sleep stage detection, e-Commerce, Fitbit Health Solutions etc. The UI (see below) consists of 3 panels: Status, Summary and Timeline. Each panel below represents one of the APIs a team implements. Once one or more (potentially all) of the APIs are implemented, they come together to provide the most value in the “Analysis” part of data processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*fdxzIrzwWugiHBnP" /></figure><h3>APIs:</h3><p>The following APIs form the core of the framework that teams need to implement to integrate with SMART gateway.</p><h3>Status</h3><p>The status endpoint returns a list of high level indicators relating to a given service or feature and its health. The UI then exposes the various statuses to give a quick overview of what features may need attention. Statuses are implemented and displayed as a color system:</p><ul><li>Green: The feature is working as intended</li><li>Yellow: There may be an issue with the feature</li><li>Red: There are problems with this feature</li><li>Gray: The given feature is not applicable</li></ul><p>Each status also gives a brief description of why it is of the chosen color.</p><p>Example:</p><pre>&quot;No storage reserved for personal music&quot; (Personal Music, Red)&quot;</pre><h3>Summary</h3><p>The summary endpoint contains an arbitrary list of key-value pairs that summarize the state of the feature for the given user. This can be used to display aggregates or settings around a given feature.</p><p>Example of summary key/value pairs:</p><pre>&quot;Completed feature onboarding&quot;: false</pre><h3>Timeline</h3><p>The timeline endpoint contains a detailed list of events that drive a given feature or service. It is the most detailed of the endpoints, and therefore is only used when serious analysis is required. The only requirement is that each event has a timestamp. Other event details are up to the implementers. The column name and values are dynamically displayed in a table form in the UI based on the API payloads.</p><p>Example event log:</p><h3>Funnel Approach:</h3><p>These APIs are used to greatly simplify diagnosability using the UI tool by using a <em>funnel approach</em> to provide the information needed to quickly narrow in on any potential problems being experienced. When we drill down further into the summary information, this helps tell the story of the issue. For example (see image below) If there is a “Red” failure on the battery, it may show up as average discharge time of their battery (summary trends) being much shorter than normal leading to quick diagnosis of their problem. If the summary details are not enough to pinpoint the issue, we can quickly load up the timeline (detailed annotations) portion to see all the battery annotations for that device in the Timeline Debug portion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*JbUg6u4xXOqGJ9m9" /></figure><h3>Implementation:</h3><p>At Fitbit, most of our service infrastructure communicates internally via Apache Thrift ( <a href="http://thrift.apache.org/">http://thrift.apache.org/</a>) using the Finagle stack ( <a href="https://twitter.github.io/finagle/">https://twitter.github.io/finagle/</a>) and many of the services we need to support do not expose HTTP endpoints that are usually more conducive for web clients. In order to make integration as easy and painless as possible, we created the Smart Gateway microservice in order to translate internal endpoints communicating via Thrift to web endpoints communicating via HTTP. This allows for those thrift endpoints to be easily consumed by our tools webpage as well as other custom platforms. For teams looking to integrate with Smart Gateway (and therefore provide SMART APIs), all they need to do is to implement a Thrift server matching the SMART API specification. Smart Gateway then registers an appropriate set of URLs that proxy the Thrift Server to our API domain.</p><p>Feature teams are free to implement as much of the SMART API specification in their Thrift server as it makes sense for them. Most teams find that their integration with Smart Gateway ends up taking less than a day of work. Furthermore, by pushing the responsibility of API implementations onto feature teams, they have the power to update the content of their SMART API responses on their own deployment schedules leading to development agility.</p><p>Currently, these APIs help quite a few teams with their numerous data diagnosis use cases. We already have over 25 integrations and counting.</p><h3>Conclusion:</h3><p>We have discussed how a simple approach of a robust UI together with a generic API design can help improve cross team collaboration, self sufficiency and efficiency. At Fitbit we constantly aspire to innovate not only to improve our user’s fitness and health tracking but also to come up with solutions internally to empower and enable teams to provide the best possible work experience.</p><p><em>Originally published at </em><a href="https://eng.fitbit.com/keep-it-simple-and-smart-kiss/"><em>https://eng.fitbit.com</em></a><em> on August 26, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1269814dd03f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fitbit-tech-blog/keep-it-simple-and-smart-kiss-engineering-fitness-1269814dd03f">Keep it Simple and SMART (KiSS) — Engineering Fitness</a> was originally published in <a href="https://medium.com/fitbit-tech-blog">Fitbit 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[Introducing Project Golden Gate — Engineering Fitness]]></title>
            <link>https://medium.com/fitbit-tech-blog/introducing-project-golden-gate-engineering-fitness-2d68db055ccc?source=rss----71d55fdd6fe---4</link>
            <guid isPermaLink="false">https://medium.com/p/2d68db055ccc</guid>
            <dc:creator><![CDATA[Gilles Boccon-Gibod]]></dc:creator>
            <pubDate>Tue, 05 May 2020 23:10:56 GMT</pubDate>
            <atom:updated>2020-05-05T23:10:56.243Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introducing Project Golden Gate — Engineering Fitness</h3><p><em>An open-source framework to connect wearables and other IoT devices to mobile phones, tablets and PCs with an IP-based protocol stack over Bluetooth Low Energy</em></p><h3>TL;DR</h3><p>If you wished your wearable or IoT devices and mobile applications could communicate over Bluetooth Low Energy as seamlessly, securely, and reliably as if they were on an IP network, using familiar internet protocols rather than low level APIs, this open-source cross platform project is the missing link that can get you there.</p><h3>Ubiquitous Bluetooth Low Energy</h3><p>At Fitbit, we have been transferring data back and forth between wearable devices and mobile phones for years leveraging Bluetooth Low Energy (a.k.a. BLE). BLE is a great base technology for our purposes. It allows low-power, short distance, bi-directional communication with a reasonable throughput. But that’s not what we like the most about it. Its best asset, bar none, is that it is essentially ubiquitous. You’d be hard-pressed to find a mobile phone, tablet or laptop today that doesn’t come with built-in BLE support. That means that we can ship our devices with a BLE radio and communication stack and know that they will be able to connect to our mobile app running on any mobile phone, tablet or laptop sold in the past few years. However, support for BLE, and our usage of it, looks very different now from what it did when we started working with it.</p><h3>Our First Generation Stack</h3><p>Supporting BLE in mobile apps isn’t always a walk in the park. In a <a href="https://eng.fitbit.com/what-is-bitgatt-and-why-do-we-need-it/">previous blog post</a>, we’ve talked about some of the issues we’ve faced, the work we’ve done to work around them, and why we released an open-source library to help others facing the same issues. That was just the start. The challenge of using and supporting BLE connections between devices and mobile apps at scale, across many different models, is much broader in scope. In our early days, all we needed to exchange between our trackers and our mobile app was limited to not much more than some steps counts, device logs, configuration data and the occasional firmware update. That’s something we could reasonably support with a simple ad-hoc exchange protocol. By the time we shipped our first smart watch, the Fitbit Ionic, in the fall of 2017, things had evolved a lot. By then, the complexity of our communication needs had grown considerably, with dozens of data types, messages, payloads, both realtime and bulk, that needed to be shuttled between our mobile app and our devices. Between on-device sensor and activity data, application data, WiFi configuration, bi-directional file transfers, GPS data and more, we found ourselves clearly at the end of what we could achieve with our first generation protocol, and with a vision of where we wanted to go next. We knew we needed to add support for messaging for apps that were being developed for our platform, had plans to add voice features for future devices, as well as many more new features and functionality in the works. So we took some time and looked for a model that would get us there.</p><h3>What We Needed Next</h3><p>At a high level, our requirements were reasonably easy to articulate: we needed a protocol that would support security (data encryption and signing for privacy and integrity), multiplexing (many subsystems communicating at the same time without interrupting each other), reliability (our devices strive to be constantly connected when in range), with a programming model that would feel familiar to both embedded and mobile developers. The protocol would need to be robust enough that we could support tens of millions of users with very different environments, yet simple enough that we could implement it on very small footprint embedded systems (we’re talking about a few kilobytes of RAM and flash here on low power MCUs). Well, as it turns out, we didn’t need to reinvent the wheel. Those are more or less the same requirements that every internet-connected system has today. Protocol stacks with HTTP, WebSockets, CoAP, TLS, TCP/IP are what billions of connected devices use today to talk to each other and communicate with the cloud in this same manner. So it became clear to us that if we could find a way to embrace that model, rather than create a parallel proprietary solution, we’d have a strong solution. Our work, then, was to pick the right subset and profiles from the available “internet standards” and figure out how to make them work within the constraints of our ecosystem. That meant that we needed to create and maintain an implementation of those standards that we could run on various RTOS (Real Time Operating Systems) as well as mobile and desktop operating systems, including iOS, macOS, Android and Windows. Furthermore, we needed to be able to transport all that protocol data over BLE (while BLE isn’t the only link we support, it is clearly a must-have for us).</p><h3>BLE’s Additional Challenge</h3><p>As we just mentioned, IoT devices communicating over low power radios with an IP-based stack isn’t anything new. For example, Nest thermostats and smoke alarms use a similar approach to networking, using the IP-based <a href="https://www.threadgroup.org/what-Is-thread">Thread protocol over 802.15.4 radio networks</a>. The additional challenge here is that we want our systems to work with BLE, because it is supported by almost all mobile phones. Technologies like WiFi are also supported, but are too power-hungry for an always-on connection on a battery-powered wearable device. And while 802.15.4 is also a low-power technology, it isn’t natively supported by mobile phones.</p><p>The Bluetooth standard does, in theory, support IP communication, with the <a href="https://www.bluetooth.com/blog/bluetooth-meet-the-internet-internet-say-hello-to-bluetooth/">IPSP profile</a>. But, when you write a mobile application for iOS or Android, the only thing that really counts is whether the operating system on which you run implements the features that you need, and what APIs are available to access those features. IPSP isn’t offered on iOS or Android, so, unfortunately, we can’t use it. What is available across the board to communicate over BLE is GATT ( <a href="https://www.bluetooth.com/specifications/gatt/">Generic Attributes Generic Attribute Profile</a>). In a nutshell, GATT gives you the ability to read/write/notify small values (up to 512 bytes) across a connection. And the reliability of communicating over GATT is a mixed bag, especially when considering the realities of how different Bluetooth stacks behave across radio chipsets, RTOS and mobile operating systems. So we needed to come up with some way to bridge that gap. What we ended up with is a simple, reliable, windowed, streaming protocol that is optimized to run well over GATT. We simply call it “Gattlink.” That link layer is what completes our network stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zw6Sd87FGqvSjMBY" /></figure><h3>Introducing Golden Gate</h3><p>Golden Gate is the name we choose for this project, our second generation communications framework. It includes a complete networking stack, starting with CoAP (Constrained Application Protocol) at the application layer, to DTLS, UDP/IP in the middle layers, to Gattlink and BLE GATT at the bottom layers. The implementation is entirely cross-platform; it runs on several flavors of RTOS, iOS, Android, macOS, Windows and Linux. It has been our standard framework since September 2019 when we launched Versa 2, which runs Fitbit OS 4. Now that we’re confident that it works great in the field, we decided it was time to share what we’ve implemented. While our products are packed with unique innovations that are tailored to our requirements, focused on health and fitness, the underlying communications stack is, by design, generic in nature. We think that our design and implementation can be used for a large number of IoT and mobile use cases, where reliable, secure, IP-based protocols offer a familiar model for developers to use, allowing them to focus on the features of their own devices and apps, rather than the underlying protocol stack. We hope that many of you, whether engineers building commercial products, hobbyists or students, will find what we’re sharing useful, and that some of you may even choose to contribute back to the project and help improve it as it evolves. We’d love to see our code adopted and used in ways we haven’t yet dreamed of, ported to other platforms, chipsets and operating systems.</p><p>We chose the name Golden Gate, because it is the name of the famous International Orange (#F04A00) colored bridge in our beloved city of San Francisco, where Fitbit’s headquarters are located, and naming the project after a bridge seemed befitting a framework whose goal is to connect things. We hope you’ll like the name too.</p><h3>How To Get Started</h3><p>To find out more, and maybe start experimenting and developing with the code, visit our <a href="https://github.com/Fitbit/golden-gate">GitHub project</a>. Please let us know what you think, and help us make it better with any feedback you may have, or even contributions.</p><h3>About the Author</h3><p><strong>Gilles Boccon-Gibod — Engineering Fellow</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kgb6vJoom9UEGWMO" /></figure><p>Gilles has been with Fitbit engineering for over 3 years where he has worked on various projects, including music services and the Fitbit Developer Platform. Most recently, he worked with the cross-functional team that has developed and integrated our new comms stack. When he’s not busy with his day job, he enjoys cooking international cuisine and sailing his Hobie Cat in the San Francisco bay.</p><p><em>Originally published at </em><a href="https://eng.fitbit.com/introducing-project-golden-gate/"><em>https://eng.fitbit.com</em></a><em> on May 5, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d68db055ccc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fitbit-tech-blog/introducing-project-golden-gate-engineering-fitness-2d68db055ccc">Introducing Project Golden Gate — Engineering Fitness</a> was originally published in <a href="https://medium.com/fitbit-tech-blog">Fitbit 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[A machine learning solution for detecting and mitigating flaky tests]]></title>
            <link>https://medium.com/fitbit-tech-blog/a-machine-learning-solution-for-detecting-and-mitigating-flaky-tests-c5626ca7e853?source=rss----71d55fdd6fe---4</link>
            <guid isPermaLink="false">https://medium.com/p/c5626ca7e853</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Serban Liviu]]></dc:creator>
            <pubDate>Wed, 09 Oct 2019 09:53:50 GMT</pubDate>
            <atom:updated>2019-10-09T09:56:52.266Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are a developer you’ve probably experienced flaky tests or flakes and the first thing that comes to your mind is either frustration or annoyance. In this post we are going to discuss how we are dealing with flaky tests here at Fitbit and what our plans are for solving this problem.</p><p>Before we go into any details, let’s level set on what flaky tests are, why they are bad and also go through some real life examples of flaky tests, just to have the context well set up. Let’s dig in!</p><h3>What is a Flaky Test?</h3><p>A test which passes or fails in a nondeterministic way is referred to as flaky. Such behavior could be harmful to developers because test failures do not always indicate bugs in the code. Broadly there are two main types of flaky tests. Those that are flaky due to some external conditions, such as network issues, machine crashes, power outages etc. Let’s say you had a test that ran on a Jenkins executor that crashed with a kernel panic, forcing you to rebuild. On the second run everything was fine and thus the test was green. So although the test passed and failed on the same Git revision, it’s not really its fault, and there is not that much we can do about a crashed executor in this context. Also network issues in integration tests cause a lot of flakiness that we cannot control. The second type of flakiness is due to defects in the test case’s code or in the CUT(code under test), such as asynchronous waits, concurrency issues such as race conditions, priority inversion or incorrect assumptions about timezones or database ordering. This type of flakiness is not that trivial to cope with because we are dealing with subtle “bugs” in the test cases themselves. In general flaky tests due to <em>test </em>programming errors are much harder to catch or identify than to find bugs in production code. We’ll see why in a second.</p><h3>Show me a real life example</h3><p>According to an analysis published by the University of Illinois in this <a href="http://mir.cs.illinois.edu/~qluo2/fse14LuoHEM.pdf">paper</a>, almost 45% of flakes are due to asynchronous waits. This number turns out to hold for our monorepo as well. Most of the flakes that we see are due to this kind of condition.</p><p>Usually this goes like this. Before the test runs, an embedded Cassandra or HTTP server is created. In the test we do an async call to the server, and then we wait in a <em>Thread.sleep()</em> call for a while, hoping the server had enough time to process our request. After that we do an assert of some kind. This generally works, except when communication lag or other network issues cause the Thread.sleep(period) to be too short. Then what? Well if there is an assert after that sleep call, then it will fail. Let’s look at a real life flaky test to get a feel of what we are up against.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Wzicyy4eTr-yIBl9vQiKg.png" /></figure><p>In this test we create a kafka producer that posts 5 messages to a topic. We also create a consumer that should consume those messages. The catch here is the <em>postMessage()</em> method is asynchronous and the kafka consumer waits for 10 seconds for the messages. In most cases this code and the final assert will work. But what if something went wrong, and 10 seconds are not enough? The assert will fail because the number of messages produced and consumed (batchSize) are not equal. This is a clear example of a test that could be flaky because of asynchronous calls to external services.</p><h3>What other types of flakes do we see?</h3><h4>Incorrect assumptions about database table ordering</h4><p>Let’s suppose you have a MySQL integration test where you create mocking data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*6C4jb7GRF8tI1E_0Ad2VHQ.png" /></figure><p>Now a simple JDBC code like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*PnNhpLKmmjnn6s8MZMhuHQ.png" /></figure><p>can make your test flaky. You have incorrectly assumed selecting the first row is guaranteed to yield 1.</p><p>The output of the SQL above can either 1 or 2 depending on a bunch of factors that are internal to the database and not the code under test.</p><h4>Resource leaks</h4><p>Another frustrating, flake causing issue are resource leaks.They can happen when an integration test suite starts an embedded HTTP server, runs a bunch of tests but leaves the server open on port 8080. If another test suite tries to use port 8080 on the same machine, it will fail because the port was already allocated.</p><p>Of course, the list could go on and on. For a more comprehensive list of types of flaky tests checkout Martin Fowler’s <a href="https://martinfowler.com/articles/nonDeterminism.html">excellent article</a>.</p><p>As you can see, finding flaky tests in a huge repository with more than 100 projects is not an easy task. And the most damaging problem related to flaky tests is not that you have to rebuild when they fail, although wasted time is certainly an issue. More important is lost confidence in tests that fail.</p><h3>Our current infrastructure</h3><p>We have a large monorepo with more than 100 projects in it, with a total of 28572 test cases and there are more than a dozen teams managing all these projects. Given this setting, just looking with your naked eye at the whole code and trying to catch flakes is certainly not a very smart strategy. It was obvious that we needed a tool to track all of these flakes, sort them by teams and make the teams aware of those tests in the hopes that they will get fixed.</p><p>One obvious way to track these is to record all the builds and all the test executions in a large database. We record everything from the git revision, to the duration of each test to the build id on which that test ran, etc. We then developed a service that looks into this database and tries to detect which test was flaky and on which build. We’ve also developed a nice dashboard that displays all of that :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oNaG2PgN4C54VdIq" /></figure><p>And in order to drive these flakes out in the open, so developers are aware of them and start fixing them, we send a weekly update with whatever flakes we’ve discovered.</p><p>We’ve quickly realized that the simple formula where we classify a test as flaky or not based on if it’s failing and passing on the same revision is not enough. We need a deeper analysis of a test’s execution history. The reason for this is that we’ve seen both false positives, tests wrongly classified as flakes, and false negatives, flakes not caught by flaky-test detector. We’ve developed a machine learning proof of concept that could track flaky tests better and “look” at them before execution in Jenkins and tell if they are flaky or real test failures. If they are flaky we can chose not to run them so they won’t block anyone from merging their code changes.</p><h3>A machine learning based solution</h3><p>There has been some research on how to distinguish between flaky tests and actual test failures. By far the most comprehensive one was <a href="https://www.youtube.com/watch?v=CrzpkF1-VsA">done at Google</a>. After some research of our own, we have developed some intuitions about flaky tests and how their execution history looks compared to that of failing tests or working tests. We know that a test is flaky if it passes and fails on the same git revision. But we also looked for tests that are passing and failing across multiple git revisions over a certain period of time. Flaky-Detector is looking for tests that are passing and failing on the same revision. That is just fine, since it follows the actual definition of a flaky tests. And we do get pretty good results. But apparently that seems not to be enough. The reason behind that is that tests that are truly flaky have certain properties attached to them.</p><p>Below are the properties we have found common across flaky tests.</p><h3>Flaky tests pass and fail on successive git revisions over a long period of time</h3><p>This property catches the flakiness better than just looking for individual revisions(as we do now).</p><p>In order to catch this aspect of a test passing and failing on several successive revisions, we’ve come up with the concept of edge. An edge for a certain test case is a transition from pass to fail or fail to pass on two different git revisions. Say you push some code change and the execution of <em>test_case()</em> passes, someone else then pushes some other changes that trigger that same test to run if it fails on the second run. That would be an example of an edge. The test <em>test_case()</em> was passing on a revision but then failed on the next revision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ey_IHnHkrgH9xS8k" /></figure><p>Looking on the image above, you could see the execution history of two hypothetical test cases over a period of 12 hours in which several Jenkins builds ran with different revisions. The first test had only two transitions. The first one from pass to fail and then the second from fail to pass and then it stayed green for the rest of the time. We cannot say the same thing about the second test which exhibits a more unstable behaviour pattern with many more transitions. From this image alone we could say that there is greater likelihood that test case 2 is flaky whereas test case 1 is not.</p><h3>Failed test cases are highly likely to be flaky if they are “far” in the monorepo from the actual code change</h3><p>We are using a monorepo where we have all our microservices and core libraries. We’ve also defined dependencies between projects. A project might depend on other projects. And those projects in turn might depend on others and so on. Say we’ve changed a java file in a core library called <strong>A</strong>. Projects <strong>B</strong> and <strong>C</strong> depend on that library <strong>A</strong>. And in turn project <strong>D</strong> depends on project <strong>B</strong> and project <strong>E</strong> on project <strong>C</strong>. Thus that change on project <strong>A</strong>, will trigger not only the unit/integration tests on project <strong>A</strong>, but also the tests on all the transitive dependencies to it, including those for <strong>B,C,D</strong> and <strong>E</strong>. See image below for the dependency tree in this example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3geGQQ5GfkvV_u7d" /></figure><p>In this contrived example, tests from project <strong>A</strong> are at distance 0 from the actual code change. But tests in projects <strong>B</strong> and <strong>C</strong> are at distance 1, whereas tests in the projects <strong>D</strong> and <strong>E</strong> are at distance 2 from the actual code change in project <strong>A</strong>. So the “farther” a test that fails is from an actual code change on that revision, the higher the probability that it’s flaky.</p><h3>Test cases that fail due to changes in config files are very likely to be flaky</h3><p>Although it is quite possible to change an xml file or any other config file, a test failure to be a real failure. Maybe a url was changed that made that test to fail. That does not mean that the test is flaky. But in general, a test that failed on git revision where only config file were changed, is highly likely to be flaky.</p><h3>A test case that has failed on a git revision that changed a file that was previously changed a lot is highly likely to be a real failure and not a flake</h3><p>Based on the idea that changing a file that was previously changed many times before could introduce bugs, we also believe that tests that fail in revisions that changes heavily modified files are more likely to be real test failures rather than flakes</p><h3>A test case that has failed on a git revision that changed a file which was previously changed by more than two authors recently is highly likely to be a real failure</h3><p>Just like the condition before, a file that was modified by more than one person is generally prone to introduce new bugs in the system. So a test that has failed on a git revision that has changed a file that was previously changed by more than two developers, is highly likely to be a real test failure rather than a flake</p><h3>A test case that has failed on a git revision where many source code files were changed, is highly likely to be a real failure</h3><p>This third condition is very much related to the previous two. Creating pull requests that change many files, across many projects in the monorepo has the potential to introduce bugs. So therefore test that tend to fail on a revision like that are highly likely to be real test failure rather than flakes</p><h3>Now what?</h3><p>Given the fact that we have all this info in our test execution database, now we have to gather all this info and use it as training data. For each test failure recorded in the database, we will look at that revision and get the list of files, and for each file get all git related info such as how many commits were done on that file, by how many authors etc. And also get the edge history(passed/failure) since that revision. All this info about each test failure, will be added to a vector that will represent a <a href="https://en.wikipedia.org/wiki/Feature_(machine_learning)">feature vector</a>. These feature vectors will then be used to distinguish between real test failure and flaky candidates using a simple unsupervised machine learning model called <a href="https://www.datacamp.com/community/tutorials/autoencoder-keras-tutorial">autoencoder</a>.</p><p>Since we do not have an annotated training set, the first step is to see how the data looks like. We will first train a separate autoencoder with some of the data that we’ve gathered from the database just to get a glimpse of how the data is spatially distributed.</p><p>Here we could use any unsupervised clustering method. Technically a simple K-means algorithm would work as well. The feature vectors that we’ve talked about earlier are multidimensional. We cannot view them in a large dimensional space. So we will do a <a href="https://en.wikipedia.org/wiki/Principal_component_analysis">PCA</a> for dimensionality reduction, to map them from their initial higher dimension into two dimensions. We can see that the data is smoothly scattered into two main clusters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ATLMo7opKeZJnQMO" /></figure><p>Looking into some individual data points from both clusters we’ve realized that the red one corresponds to flaky tests whereas the blue one to real test failures. Just as we’ve discussed earlier, flakes in general have higher number of pass/fail edges in their execution history and they tend to correspond to git revisions where mostly config files were changed and the “dependency distance” between the changed code and the test is higher on average. These conditions are enough to cluster the flakes in a different cluster from the actual test failures that have on average a lower number of pass/fail edges and they happen on git revisions where either multiple files were changed or files that were changed many times by many authors, and those files are source code files on average.</p><h3>That’s it?</h3><p>Well not really. Getting a feel of how that data looks like is not enough to classify a test as either flake or failure. What we want in the end is a method that works directly on the Jenkins machines and could “look” at a test case and tell you before you run it if it is a flake or a real test failure. In case we’re dealing with a flake, we’ll ignore it if it fails so it does not become a nuisance to developers. What we need is to have the ability to classify between those two classes. What we’ll do, is we will train another multilayer autoencoder just with the failures that we managed to infer from the clustering. After that we will have a trained autoencoder that could reconstruct failure feature vectors.</p><p>Autoencoders are a specific type of feedforward neural networks where the input is the same as the output. They compress the input into a lower-dimensional code and then reconstruct the output from this representation. The code is a compact “summary” or “compression” of the input, also called the latent-space representation.</p><p>An autoencoder consists of 3 components: encoder, code and decoder. The encoder compresses the input and produces the code, the decoder then reconstructs the input only using this code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/0*v9I0ZdFDkDPvdxqX" /></figure><p>A simple autoencoder that is trained to reconstruct simple digit images.</p><p>We’ve trained an autoencoder to learn the internal representations of real test failures. Therefore failures in this model will have a small reconstruction cost, whereas flakes will have a large reconstruction cost. For more info on neural networks and their cost functions check out this awesome <a href="http://neuralnetworksanddeeplearning.com/">mini book</a> by Michael Nielsen</p><p>In order to predict whether or not a new/unseen test case failure is real or flaky, we’ll calculate the reconstruction error from the test failure data itself. If the error is larger than a predefined threshold, we’ll mark it as a flake (since our model should have a low error on real test failure).</p><p>Let’s now plot each failure’s cost to see how they look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LXzS_dDgmQF9IPua" /></figure><p>It’s clear from this picture that the maximum reconstruction cost for failure is somewhere around 40. Let’s pick this value as the threshold.</p><p>Now let’s feed-forward the feature vectors for the flaky samples and plot them along with the real failures and see how they differ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RClijtK6QJql8BZ4" /></figure><p>The orange points represent flakes and the blue ones are the failures. The red line is our chosen threshold. We can see a clear separation between the two sets!</p><h3>Why not a supervised binary classifier like SVM instead?</h3><p>Because in order to use a support vector machine or a feed forward neural net we would need an annotated training set. So as you might’ve guessed already, that would take a huge time effort and a lot of manual labor. And that’s something we cannot afford. So we wanted to have a method that is unsupervised, or to be more precise, semi-supervised, where we first get a geometric understanding of the data and sample a few hundred samples from the failure data and train an autoencoder in order to learn their internal representation. Then use anomaly detection where flakes are treated as anomalies in this model.</p><h3>Results</h3><p>In the simple example from above, samples that have a higher reconstruction error than 40 are very likely to be flakes. To check that even further let’s look at the <a href="https://en.wikipedia.org/wiki/Confusion_matrix">confusion matrix</a> of this model :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JDKCOxSE4A8sV_bE" /></figure><p>So out of 802 flaky tests in the test set, all of them have been detected as flaky. We could say that we have precision 100% and zero false positives.</p><p>Out of all the 19271 of real failures in the test set, all of them have been classified as failures by our model, and none of them as a flake. We could say that our model performed flawlessly. This is the type of model that is used in malware detection or credit card fraud detection. In this environment, you should not fail to predict a normal transaction as fraudulent or even worse a fraudulent one as normal. That would be very very bad!!! That’s why we’ve chosen an anomaly detection algorithm using an autoencoder and not a classification algorithm such as support vector machine or logistic regression.</p><h3>In Conclusion</h3><p>We hope this has been an informative look into how handle flaky tests how we’ll go about detecting them</p><p>If you love finding bugs and flaky tests as much as I do, and love writing great software that inspire a healthier, more active lifestyle, come join us at<a href="https://www.fitbit.com/careers"> fitbit.com/careers</a>!</p><p>About the Author</p><p><strong>Liviu Serban — Senior Software Engineer</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/0*Zaz1nsqZ-UUlV1HQ" /></figure><p>Liviu has been a software engineer at Fitbit for almost 2 years, and has worked in the developer productivity team where we try to make the lives easier for the rest of the developers, by making sure that core services such as Jenkins are in good shape. When he is not investigating failures in Jenkins builds, Liviu likes to learn about machine learning, and enjoys going out with friends.</p><p><em>Originally published at </em><a href="https://eng.fitbit.com/a-machine-learning-solution-for-detecting-and-mitigating-flaky-tests/"><em>https://eng.fitbit.com</em></a><em> on October 9, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5626ca7e853" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fitbit-tech-blog/a-machine-learning-solution-for-detecting-and-mitigating-flaky-tests-c5626ca7e853">A machine learning solution for detecting and mitigating flaky tests</a> was originally published in <a href="https://medium.com/fitbit-tech-blog">Fitbit 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[The Tower of Terror: A Bug Mystery]]></title>
            <link>https://medium.com/fitbit-tech-blog/the-tower-of-terror-a-bug-mystery-c57f51981eff?source=rss----71d55fdd6fe---4</link>
            <guid isPermaLink="false">https://medium.com/p/c57f51981eff</guid>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[fitbit]]></category>
            <category><![CDATA[firmware]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Shiva Rajagopal]]></dc:creator>
            <pubDate>Wed, 11 Sep 2019 21:49:00 GMT</pubDate>
            <atom:updated>2023-09-25T07:05:52.267Z</atom:updated>
            <content:encoded><![CDATA[<p>Here at Fitbit, we are no strangers to shipping hardware products. Making a new product is not an easy task, especially as we approach its ship date. During this time, our employees (both inside and outside of engineering) are a key part of testing the product and getting as many testing hours as possible. We encourage our employees to wear the device during their everyday lives, stress test them, and put them through any scenarios they can think of, no matter how weird.</p><p>For those of us working on the firmware (our general term for software that runs on the device), this time is filled with fixing bugs and tweaking the system to make it as polished and stable as possible. Like any deadline, a lot of hard work goes in near the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*sgYohU4H-yoSAV-e.gif" /><figcaption>Pair programming gone wrong: Two people on one keyboard usually ends poorly (<em>source: CBS</em>)</figcaption></figure><p>This can certainly make for a stressful time, but sometimes there are little bugs that catch your attention and make you laugh. One such bug came across my desk during the final push before we launched the Fitbit Ionic. We thought this would make for a great example of how we test devices internally before they launch, and how our firmware team investigates crashes and bugs on our devices. Buckle up and strap in, it’s going to be a fun roller coaster ride.</p><h3>Bugs and Bug Reports</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/0*_pIxpwMEGSYDP76b.png" /><figcaption>Starship Troopers is even relevant to programming (<em>Source: Tristar Pictures</em>)</figcaption></figure><p>Bugs within the firmware team can take many forms including, but not limited to, the device crashing and rebooting. Sometimes these occur during normal usage and most users don’t notice. Other times are more obvious, like when the user is actively interacting with the device. Our devices report all crash information back to our servers so that we can know our top crashes regardless of whether users report it or not. However, crash reports can’t always give us all the information we need to fix a bug. Oftentimes, there are multiple paths to get to a certain line of code, and sometimes there can be multiple triggers for a certain code path. Without data about what was happening at the time, it can be difficult to reproduce the bug and be sure that we have fixed it.</p><p>This is where bug reports from our testers are indispensable, as they tell us what they were doing with the device at a certain time of day, (for example, exercising, sleeping, using an on-device app, hiking in a certain location, etc.). Like any good mystery, every clue is helpful in hunting for bugs. Bug reports usually take the following format:</p><ul><li><strong>Summary of the issue</strong></li><li><strong>Steps to Reproduce</strong></li><li><strong>Reproducibility Rate</strong></li><li><strong>Firmware Version</strong></li><li><strong>Smartphone App Version</strong></li><li><strong>Any other info the tester can provide (date/time of occurrence, etc.)</strong></li></ul><p>Any/all of these fields could be filled for any given bug, but this represents a good set of information for a firmware developer to start bug hunting.</p><h3>Enter Mission: Breakout!</h3><p>If you’ve ever been to Disneyland, you’ve probably heard of the <em>Guardians of the Galaxy- Mission: Breakout!</em> ride or its predecessor, <em>The Twilight Zone</em> <em>Tower of Terror</em>. If you need clarification, here’s a <a href="https://www.youtube.com/watch?v=k0F2aLwt2d8">YouTube video</a> that gives an idea of the ride. The experience boils down to lots of very fast ups and downs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yBqGmwHQrHShVAhB.jpg" /><figcaption>Grand, bright, and terrifying (<em>Source: Disney</em>)</figcaption></figure><p>When our internal testers report a bug, the bug finds its way through our Field Testing team, and ends up on the (figurative) desk of engineers like myself. The following report showed up on my desk one day:</p><ul><li><strong>Summary of the issue<br></strong>Went on Disneyland Tower of Terror (Guardians of the Galaxy). During the course of the ride, my Ionic rebooted 3 times. I went on it twice and it was repeatable each time.</li><li><strong>Steps to Reproduce<br></strong>Ride the Tower of Terror</li><li><strong>Reproducibility Rate<br></strong>100%</li><li><strong>Any other info<br></strong><em>Date/Times of Occurrence:<br></em>Last Saturday between 5:00 and 5:30 PM, and between 6:30 and 6:40 PM</li></ul><p>Another tester saw this report, and added on a comment:</p><blockquote><em>I had this happen a few times. I was at Six Flags Magic Mountain and rode a ton of roller coasters.</em></blockquote><p>Needless to say, my team and I got a good laugh out of this one. After the laughter died down, I buckled down to hunt for the bug and fix it. But before I dive into that process, let’s take a small detour into how Fitbit devices work.</p><h3>Accelerometers</h3><p>Accelerometers are in virtually every device that tracks motion these days, and they do exactly what you’d expect based on their name: they measure acceleration. These are in your smartphones, drones, and of course, the Fitbit devices you know and love. We use 3-axis accelerometers to get the data we need for many of our stats. The directions of the 3 axes (X, Y, and Z) can vary across products, but here’s an example for the Fitbit Blaze:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/0*ZDS7MShhml_bZ5gq.png" /><figcaption>Accelerometer axes on a Fitbit Blaze (<em>Source: Fitbit R&amp;D</em>)</figcaption></figure><p>Our accelerometer is active and taking measurements as long as the device is powered on, and constantly delivering 3-axis data to our algorithms like step-counting, automatic exercise detection, screen wake, and many others. While you’re walking, for example, the accelerometer data looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Zr9pnkJf1z7Tek2w.png" /><figcaption>Acceleration vs. time, Axes separated (<em>Source: Fitbit R&amp;D</em>)</figcaption></figure><p>This graph may look weird, because two of the axes are close to each other, but the third is far below the others. Why is that? If you guessed “gravity,” good job! By virtue of being on the planet Earth, our accelerometer will always report 1g of acceleration, as that’s what it takes to resist the force of gravity. If you’d like more information as to why, <a href="https://www.phidgets.com/docs/Accelerometer_Primer#Gravity_vs._Acceleration">this article</a> can explain the concepts much better than I can.</p><p>In the case of this graph, you can fairly easily guess where the steps are happening by looking at the peaks on each line. Let’s make it even easier though. In 3 dimensions, the X, Y, and Z components create a 3D <strong>vector</strong> that can give us the overall magnitude and direction of our acceleration for each point in time. If we took this same data and graphed the <strong>magnitude</strong> of the vector through time, it looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t5jjWOFW4ykinz2D.png" /><figcaption>Acceleration magnitude vs time (<em>Source: Fitbit R&amp;D</em>)</figcaption></figure><p>Even easier to find the steps now, right? Also as expected, our magnitude is centered around the 1g of force that we expect, and the peaks/troughs on the graph can tell us where the steps are. Our step-counting algorithm is far more complex than this, but this is just a simple example of how one could use an accelerometer to count steps.</p><p>This entire digression about accelerometers is meant to show that they give us a lot of data, and even a little bit of processing on the data can help us understand what the user might be doing. Remember the concept of magnitude, it’ll come in handy later.</p><h3>Following the Breadcrumbs</h3><p>Okay, so back to figuring out what happened on the roller coaster. The first place we look when a crash is reported is the device crash records. If you’ve ever seen the Blue Screen of Death on Windows, you’ve probably seen a whole bunch of data that makes little obvious sense. The same would be true for our crash logs. While these logs can look intimidating, data like this can tell us a lot of what we need to find a bug. Here’s an example:</p><pre>Fault Log: Link Register 0x10018f31, Program Counter 0x10019064 Fault Register 0x00002000<br>Stack Trace: 0x10018f31 0x10019064 0x10018f31 0x1001bc17<br>Stack Trace: 0x10036401 0x00000000 0x00000000 0x00000000<br>Stack Trace: 0x00000000 0x00000000 0x00000000 0x00000000<br>Stack Trace: 0x00000000 0x00000000 0x00000000 0x00000000</pre><p>After translating this log against our code base, I found the data I needed to start tracking this bug down:</p><pre>Crash Cause: System tried to divide by zero<br>Location of offending code: AddNewSamples function at algorithm_x.c, line 500</pre><p>Yay! We now know why our device crashed, and where in our codebase it crashed. As expected, our system panics and crashes when we try to divide by zero in our algorithm code. Our algorithms perform many mathematical operations, and any abnormalities can have unexpected effects on your stats, so we need to catch these errors and ensure we fix them.</p><p>The next step after translating the crash data is to look at the code where the divide-by-zero occurred, so let’s go find line 500 of the algorithm_x.c file. Here’s a snippet very much like that line of code.</p><pre>500: scaled_accel = (SCALE_ACCEL * raw_accel_mag) / filtered_accel_mag;</pre><p>Admittedly, this code is a little opaque without more context, but it boils down to scaling the ratio between a raw accelerometer magnitude and a filtered accelerometer magnitude. This is one mathematical step in the larger context of this algorithm. To our advantage, there is only one division on this line, so we know exactly which value must have been zero to cause this crash: filtered_accel_mag. The question now becomes, how did that value become zero for us to divide by it?</p><p>The answer is, of course, physics. As you might have gleaned from the video above, the <em>Mission: Breakout!</em> ride drops you into what is effectively free-fall for several seconds, during which your accelerometer sees a zero-g environment. If you’re curious about why, <a href="https://www.phidgets.com/docs/Accelerometer_Primer#Gravity_vs._Acceleration">the article</a> I linked above has a great explanation.</p><p>Once I realized this was caused by a zero-g environment, I tried to reproduce it myself by throwing the device in the air. This would be akin to creating a moment of zero-g, and I expected it to crash the device. To my surprise, the device did not crash. After more investigation, the key to understanding why this occurred was in the name of the value: “filtered.” In this context, “filtered” means we are smoothing the data and making it less susceptible to change in a short amount of time. This meant that my experiment would not read zero-g for long enough to make the filtered value reach zero. On a roller coaster, however, the accelerometer reports zero-g for long enough that the value reaches zero and causes the crash.</p><p>So now we know why riding <em>Mission: Breakout!</em> causes the device to crash and reboot:</p><p><strong>Being in free-fall for enough time causes the filtered accelerometer magnitude value to approach zero, which makes this line of code divide by zero, thereby crashing the system.</strong></p><h3>Fixing the Bug and Releasing a New Firmware</h3><p>Now that we know why the bug happens, it’s important to find a fix for it. In the case of this particular algorithm, the accelerometer signal was only used to check for movement. Device movement during free-fall is not a big issue for us, especially since this is a fairly rare use case. This meant that we could check for the value being zero, and if so, hard-code a non-zero value.</p><pre>if (filtered_accel_mag &gt; 0) {<br>    scaled_accel = (SCALE_ACCEL * raw_accel_mag) / filtered_accel_mag;<br>} else {<br>    scaled_accel = DEFAULT_VALUE;<br>}</pre><p>Once we had implemented the fix, the only thing remaining to do was make sure our internal testers gave it a test run before releasing it to the public. Our internal testers (like many of our customers) faithfully update their firmware as soon as it becomes available, and it turns out there are many Fitbit employees willing to volunteer to test a bugfix on a roller coaster. Within short order, we had our confirmation of a fix. One such comment:</p><blockquote><em>I experienced no reboots on California Screamin’ yesterday with two rides.</em></blockquote><p>Unfortunately, being so close to launch, we could not release the fix for this bug along with Ionic’s launch. We ultimately released the fix for this bug along with a larger firmware release to support our (<a href="https://eng.fitbit.com/fitbit-sdk-tools-open-source/">open-source</a>!) SDK, which enabled third-party developers to make apps for our smartwatches. With the release, the bug was officially dead and closed. Victory!</p><h3>In Conclusion</h3><p>We hope this has been an informative look into how we handle device crashes as a team, and how we go about tracking down and fixing a bug. This is by no means the weirdest bug we’ve ever had. A few examples of bugs we’ve faced over the years:</p><ul><li>Tight pants causing excessive “floors climbed” to be measured in someone’s pocket</li><li>Connected GPS reporting less accurate distances in the Southern Hemisphere</li><li>Hardware light sensitivity throwing off power measurements.</li></ul><p>Bug fixes like this roller coaster case get carried forward to all of our future products, and as a result, our products get better and better over time. No product launch is without its issues, but we put a lot of love and care into making these devices as great as possible. Our new<a href="https://www.fitbit.com/shop/versa"> Versa 2 smartwatch</a> is the perfect example of just how far our smartwatches have come.</p><p>If you love embedded software and firmware as much as I do, and love making devices that inspire a healthier, more active lifestyle, come join us at<a href="https://www.fitbit.com/careers"> fitbit.com/careers</a>!</p><h3>About the Author</h3><p><strong>Shiva Rajagopal — Staff Firmware Engineer</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dirYy9pvKXBTB-cj.jpg" /></figure><p>Shiva has been a firmware engineer at Fitbit for 3 years, and has primarily worked on Fitbit’s smartwatches (Ionic, Versa, Versa Lite Edition, Versa 2). He served as the Firmware Development Lead for Versa Lite Edition, and loves hunting down bugs (if you couldn’t tell by this blog post). When not hunting bugs, Shiva enjoys biking around San Francisco, volunteering at the SF Exploratorium, and sampling different beers around the Bay Area.</p><h3>Acknowledgements</h3><p>Thanks to Alexandros Pantelopoulos for the data figures. Thanks to all who reviewed this post, and thanks to the Ionic team for a fun time!</p><p><em>Originally published at </em><a href="https://eng.fitbit.com/the-tower-of-terror-a-bug-mystery/"><em>https://eng.fitbit.com</em></a><em> on September 6, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c57f51981eff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fitbit-tech-blog/the-tower-of-terror-a-bug-mystery-c57f51981eff">The Tower of Terror: A Bug Mystery</a> was originally published in <a href="https://medium.com/fitbit-tech-blog">Fitbit 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[Fitbit SDK Tools Open Source]]></title>
            <link>https://medium.com/fitbit-tech-blog/fitbit-sdk-tools-open-source-5bc74e27fc7?source=rss----71d55fdd6fe---4</link>
            <guid isPermaLink="false">https://medium.com/p/5bc74e27fc7</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[fitbit]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[sdk]]></category>
            <category><![CDATA[rollup]]></category>
            <dc:creator><![CDATA[Liam McLoughlin]]></dc:creator>
            <pubDate>Wed, 11 Sep 2019 21:43:41 GMT</pubDate>
            <atom:updated>2019-09-11T21:43:41.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*3tehrCgCHF1RQV79siApWQ.png" /></figure><p>The Fitbit Developer Tools team are committed to open-sourcing the tools we’ve created for the Fitbit SDK. This enables developers to build upon our efforts with their own tooling built specifically to suit their needs, or to collaborate with other developers in the community making development for Fitbit devices even more awesome.</p><p>The Fitbit SDK Tools are built on the existing foundations of excellent open-source projects, harnessing tools and libraries such as <a href="https://www.typescriptlang.org/">TypeScript</a>, <a href="https://rollupjs.org/">Rollup</a>, <a href="https://github.com/gulpjs/vinyl">Vinyl</a> and many more! We’re happy to be able to open-source what we’ve built, and can’t wait to see what developers create.</p><h3>Available Projects</h3><p>There are currently two major components to our SDK tooling: the <a href="https://github.com/Fitbit/fitbit-sdk-toolchain">toolchain</a>, and the <a href="https://github.com/Fitbit/developer-bridge">debugger</a>.</p><p>The toolchain is responsible for compiling your project sources and assets into a Fitbit application that you can install to your device, the Fitbit OS Simulator, or upload to the Fitbit App Gallery. We provide this as part of Fitbit Studio, and also as the <a href="https://github.com/Fitbit/fitbit-sdk-toolchain#readme">@fitbit/sdk</a> package (<a href="https://www.npmjs.com/package/@fitbit/sdk">npm</a>).</p><p>The debugger is a command-line tool and a suite of libraries that allow you to interact with a device during app development. It knows how to install apps, receive logs, take screenshots and much more! This powers Fitbit Studio’s Developer Bridge integration, and the <a href="https://www.npmjs.com/package/@fitbit/sdk-cli">@fitbit/sdk-cli</a> package (<a href="https://www.npmjs.com/package/@fitbit/sdk-cli">npm</a>). Do you want to build your own awesome IDE integration? This project has everything you need to get started!</p><h3>Additional Packages</h3><p>We are also releasing some utility packages which could be useful outside of the Fitbit developer community. The <a href="https://github.com/Fitbit/jsonrpc-ts">@fitbit/jsonrpc-ts</a> package (<a href="https://www.npmjs.com/package/@fitbit/jsonrpc-ts">npm</a>) is an implementation of the <a href="https://www.jsonrpc.org/specification">JSON-RPC 2.0</a> protocol with type-checking superpowers, powered by the amazing <a href="https://github.com/gcanti/io-ts">io-ts</a>, and <a href="https://github.com/Fitbit/portable-pixmap">@fitbit/portable-pixmap</a> (<a href="https://www.npmjs.com/package/@fitbit/portable-pixmap">npm</a>) is a decoder for the <a href="http://netpbm.sourceforge.net/doc/ppm.html">Portable Pixmap</a> image format.</p><h3>Ready to contribute?</h3><p>Developers are invited to make pull requests and file issues against <a href="https://github.com/search?q=topic%3Afitbit-sdk+org%3AFitbit&amp;type=Repositories">our projects on GitHub</a>. These projects are licensed under BSD 3-Clause/MIT licenses, and we want to make contributing as easy as possible: we only ask that you agree to a lightweight <a href="https://dev.fitbit.com/community/contributing/#developer-certificate-of-origin-dco-">DCO</a>.</p><p>Get started by reading our <a href="https://dev.fitbit.com/community/contributing/">contributor guide</a> and browsing the repos available within <a href="https://github.com/Fitbit">the Fitbit GitHub organisation</a>. We can’t wait to see what you build! Share your projects with us on <a href="https://twitter.com/FitbitDev">Twitter</a> with the <a href="https://twitter.com/hashtag/made4fitbit?f=tweets&amp;vertical=default&amp;src=hash">#Made4Fitbit</a> hashtag.</p><p>About the Author:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*Xl8igWKL-76NIkdW.jpg" /></figure><p>Liam joined Fitbit in 2016 and leads the Fitbit SDK Tools team that are responsible for Fitbit Studio, Fitbit OS Simulator and the Fitbit Command Line SDK. When not hanging out on the Community Forums and Discord chatting with our Developer Community, he enjoys running, triathlon, and has completed over 300 escape rooms to date.</p><p><em>Originally published at </em><a href="https://eng.fitbit.com/fitbit-sdk-tools-open-source/"><em>https://eng.fitbit.com</em></a><em> on July 24, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bc74e27fc7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fitbit-tech-blog/fitbit-sdk-tools-open-source-5bc74e27fc7">Fitbit SDK Tools Open Source</a> was originally published in <a href="https://medium.com/fitbit-tech-blog">Fitbit 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[Load testing microservices and identifying scalability issues — Engineering Fitness]]></title>
            <link>https://medium.com/fitbit-tech-blog/load-testing-microservices-and-identifying-scalability-issues-engineering-fitness-32a2c09b6d4a?source=rss----71d55fdd6fe---4</link>
            <guid isPermaLink="false">https://medium.com/p/32a2c09b6d4a</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[jmeter]]></category>
            <category><![CDATA[fitbit]]></category>
            <category><![CDATA[load-testing]]></category>
            <dc:creator><![CDATA[Jonathan Farr]]></dc:creator>
            <pubDate>Wed, 11 Sep 2019 17:13:55 GMT</pubDate>
            <atom:updated>2019-09-11T17:13:55.154Z</atom:updated>
            <content:encoded><![CDATA[<h3>Load testing microservices and identifying scalability issues — Engineering Fitness</h3><p>Engineering at Fitbit prioritizes quality around the products that we build. We do a number of things to support this-one of them is pre-release load testing. This ensures not only that the services can handle traffic generated by millions of users, but also handle it with acceptable latencies. Fitbit commonly uses two strategies to load test services: dark testing in production and simulation in an isolated environment dedicated to performance testing.</p><p>Dark testing in production is typically a much lighter strategy to implement, as long as the request pattern to the service under test closely parallels that of an existing production service. Sometimes the work involved in setting up a funnel of traffic from an existing production service to your service under test is significant, however. In this case, the alternative of simulation in an isolated environment becomes desirable from both a flexibility and a production stability perspective.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/0*nFtGjS3l1tW_JGaU" /><figcaption>See how you rank among your friends on the Fitbit leaderboard!</figcaption></figure><p>The leaderboard service is a prime example of a service load tested at Fitbit with minimal implementation overhead using dark reads. The creation of this service supported a larger goal at Fitbit of breaking up our monolithic application into smaller, more manageable microservices. As one of these new microservices, the leaderboard service was not so much a new feature as it was a re-implementation of existing leaderboard logic in a new context. Conveniently, this sister leaderboard code in the monolith provided an easy source of fake (but realistic!) traffic to the new service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/0*HSetud5aTgHmktW2" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5MTF0-HRLAnBQpq0" /><figcaption>A monolith can be hard to change and deploy safely once it gets too large. Smaller microservices are much easier to manage and deploy separately, as needed.</figcaption></figure><p>At the onset of each call to the monolith’s leaderboard endpoints, requests to the new leaderboard service were added to an independent thread pool. An independent thread pool was used because dark reads should have as little of an impact as possible on the service handling real production traffic. This allows for the dark requests to succeed or fail as quickly or as slowly as the service under test can manage, with a minimal negative impact on the performance of the service in production.</p><p>The dark requests were also placed behind a feature flag to control the percentage of production traffic for which a dark read should be performed. This enabled us to ramp up traffic to the new microservice slowly, and scale its dedicated resources accordingly (not to mention providing a killswitch if anything were to go wrong!). Instrumentation was added both to track the latency of these dark reads and also to compare the results of the dark reads with the responses sent to users.</p><p>The success criteria of this test were quite simple-handle the full load of dark traffic representing what’s currently being serviced in production, and return an equivalent response at least as fast as the existing monolithic endpoint. There was of course some tuning done to the microservice along the way, but its independent nature allowed us to more easily learn about, tune, and release a new microservice with quality and confidence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/0*VF5t0m1__pXRu0Zc" /><figcaption>But you never know when that meteor is going to hit…</figcaption></figure><p>Sometimes a new service does not have an easy, safe, or relevant source of dark traffic. For these cases, Fitbit has a server environment dedicated to performance testing. Any or all microservices can be deployed and tested as a system in isolation there. We used this environment to ensure that the new in-app Dashboard experience (rolling out worldwide at the time of this post!) was ready to handle the traffic from millions of users.</p><p>Testing in this way is often more difficult not only in implementation but also when defining success criteria. When a microservice is meant to embody existing logic elsewhere, it should generally perform as well as or better than its predecessor. In the case of the new Dashboard experience, however, we were moving from a client-driven Dashboard to a server-driven Dashboard. It would be more trouble than it’s worth trying to replicate behavior precisely across systems with such fundamental differences. Instead we were tasked with designing a new user experience, complete with many new error cases and new requirements for acceptable latencies.</p><p>The process of load testing this Dashboard service in isolation involved three steps:</p><ul><li>We deployed the service itself with its (many) dependencies into the performance environment, where tests are regulated to prevent interference with one another and metrics can be tracked in isolation from any outside noise.</li><li>We wrote a script in JMeter to programmatically generate traffic mimicking a user’s typical request pattern when interacting with each of the service’s public endpoints.</li><li>We ran the script, pointed it at the instances deployed to the performance environment, and observed how the service behaved under progressively increasing load. This is the part where things got interesting, and where we learned the most about how the system was functioning.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/0*bVK-EkD_5CZP1H4-" /><figcaption>An example Dashboard in the new app experience</figcaption></figure><p>We ran the script for the first time, but strangely a majority of requests were failing according to the JMeter results. Even more strange was the lack of evidence of these failures in the service logs, meaning that the requests must have been rejected before even reaching the service itself. At Fitbit, we have <a href="https://eng.fitbit.com/the-passport-a-tool-for-better-metrics/">a request routing service</a> in place to collect general metrics on the traffic to all Fitbit APIs. This service seemed like a good place to begin the investigation into where these requests were disappearing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*83bLq1wmnk3e13Jc" /><figcaption>An upper limit has been reached in the number of open connections to our service under test.</figcaption></figure><p>Alas! This graph of active connections between the request routing service and the Dashboard service made it clear that we were hitting a ceiling of 300 simultaneous open connections allowed between these two services at one time. When no quota was available, incoming requests were simply failed on the spot until other in-flight requests were completed. By configuring the request routing service to allow for more active connections to our Dashboard service in the performance environment, these bursts of requests were no longer denied in subsequent tests.</p><p>While this was merely an inconvenience during the test, it did reveal a requirement to carefully estimate and configure this request routing service’s request rate limit for our service in production. If we had too low of a quota, requests would be dropped in this same way in production! If we had too high of a quota, our service wouldn’t be able to handle all of the potential incoming requests. But this would have to come later, after the load test’s results are available to inform the estimation.</p><p>The script was run for a second time to simulate linearly increasing load over a long period of time to observe when the service’s performance degraded. But again, a strange phenomenon was occurring. Traffic to the service was increasing very quickly and then remaining roughly constant for the remainder of the test, even though the number of user-threads was increasing linearly throughout the duration of the entire test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/0*Pg_iK7wtS0XxfW2o" /><figcaption>That’s not linear…</figcaption></figure><p>One key realization explains this progression-a lack of any sort of rate limiting in the JMeter user-thread loops. Although each user-thread is executed independently and in parallel, each individual thread still needs to finish an iteration of its loop before beginning its next iteration. When the only thing preventing each thread from proceeding to its next iteration is the latency of the request being made, a negative feedback loop forms. A very small number of user-threads can create a large amount of traffic when each loop iteration takes a very short amount of time. But with a large amount of traffic comes increased latencies on the service handling the traffic. Increased latencies mean longer loop iterations on each of the user-threads, and thus less traffic!</p><p>Eventually (quite quickly, in this case), an equilibrium is reached where latencies have increased and request rate has decreased to a point where the service is fully saturated. If traffic to the service were to increase, then its latencies would increase due to lack of resources and traffic would decrease. Conversely, if traffic to the service were to decrease, then its latencies would decrease due to extra resources becoming available and traffic would increase. This equilibrium provides an interesting metric on the service, representing the saturation point in requests per second that it can handle if it consumes all of its available resources. In practice, this point is not something a healthy service should ever approach, however, since the service would likely breach its SLOs well before approaching this state. Regardless, we discovered that this service as tested could handle no more than 1,250 requests per second with the resources it was allocated.</p><p>In order to get a more useful result from the load test, we had to ensure that each of JMeter’s user-threads produced a roughly constant amount of traffic over time. One simple way of achieving this is to inject into each of the loop’s iterations an artificial pause of the same magnitude as the acceptable latencies of the requests themselves. This ensures that each loop will take about the same amount of time, assuming latencies remain smaller than what is acceptable from the service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/0*VaCHFMFJ8G6IS1ky" /><figcaption>That’s more like it!</figcaption></figure><p>With the pause added to the JMeter script, we finally had a load test providing useful results! Let’s take a look at some of the graphs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/0*g_TkFe47aRNwSp0t" /><figcaption>p99 Endpoint Latencies</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/0*GRcRKAGFZnMKldNA" /><figcaption>p90 Endpoint Latencies</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/0*EuLRwFn3FslkA-5C" /><figcaption>p50 Endpoint Latencies</figcaption></figure><p>In these graphs, p99 Dashboard load times rise above 2 seconds after about 15:51. This was an unacceptable amount of latency, based on user research showing that in as little as 2 seconds users lose interest if the information they are looking for does not load. The service was deemed to be degraded after this time, because the sum of latencies was consistently over 2 seconds on the p99 graph, and latencies on the p90 and p50 graphs were also showing relatively large increases in latency. Furthermore, the HTTP status total graph begins to diverge from a linear trajectory at this time, suggesting that the total request latency within a single user loop was becoming more significant than the injected pause duration (chosen to be 1.5 seconds per loop). This results in the throughput of a single instance of this service to be about 900 requests per second.</p><p>To test this hypothesis, a second instance of the Dashboard service was deployed to the performance environment, and the test was run again. If the previous results were accurate, and the service scales linearly with the number of instances deployed as expected, then the service ought to degrade at roughly twice the load observed in the previous test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OCh9IaIpVgUahRHp" /><figcaption>Load testing, now with twice the resources!</figcaption></figure><p>Instead, although there were twice the number of instances, each appeared to be degrading at about half the rate from before, resulting in a total throughput roughly equal to the first test! A quick look at some of the Dashboard service’s upstream dependencies’ latencies revealed what might have been the issue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RwOfabLjY2hxcBQU" /><figcaption>p99 latencies of upstream requests made by the Dashboard service to other APIs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HivhFSvzRNSXRS4W" /><figcaption>p99 latencies of end-to-end Dashboard service requests</figcaption></figure><p>It appeared that a significant portion of the service’s degradation was due to its upstream dependencies. But even though the increasing latencies of the upstream requests was clearly having an impact, they do not account for the entirety of the increase in latency within the Dashboard service. To be safe, we would remain with a conservative estimate of 900 requests per second per instance based on the results of this load test.</p><p>Now we had all of the information we needed to estimate the number of instances required to support full production traffic! We estimated based on traffic to the current Dashboard that this new service would be handling about 24,000 requests per second in production. With each instance able to handle 900 requests per second, and a 30% overhead to be safe, this means that we need 34 instances to safely handle production traffic. Of course, this may be an overestimation based on the degradation of upstream dependencies that was observed, but it’s better to overestimate than underestimate! We can always release resources down the road if it looks like we have more capacity than expected.</p><p>With these results, we were confident in beginning the rollout of our new system. Of course there were bumps in the road along the way, but with a solid base provided by these tests these issues were mitigated quickly and with minimal user impact.</p><p>Soon all users will be able to enjoy the new in-app Dashboard experience, and all of the potential that comes with it. New features, new stats, and new experiences will all be supported by this platform to empower and inspire the world to live a healthier, more active lifestyle.<br>If you also appreciate quality software and inspiring a healthier, more active lifestyle, come join us at <a href="https://www.fitbit.com/careers">fitbit.com/careers</a>! And may your services run smoothly, even when the going gets tough.</p><h3>About the Author</h3><p><strong>Jonathan Farr</strong> — Senior Software Engineer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M19NwkHaIXbXv0vb" /></figure><p>Jonathan has been a backend engineer at Fitbit for 3 years (and an internship!) and has been focused on the design and development of the new in-app Dashboard experience for the past year. He plays board games every chance he can find. Some of his favorites include Hanabi, Spirit Island, Dominion, Sagrada, and The Mind. He also organizes a bi-weekly board game night at Fitbit to convince more people to play board games with him. When not playing board games, he also enjoys playing Pokémon GO around San Francisco and climbing at Dogpatch Boulders or Berkeley Ironworks.</p><p><em>Originally published at </em><a href="https://eng.fitbit.com/load-testing-microservices-and-identifying-scalability-issues/"><em>https://eng.fitbit.com</em></a><em> on August 7, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32a2c09b6d4a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fitbit-tech-blog/load-testing-microservices-and-identifying-scalability-issues-engineering-fitness-32a2c09b6d4a">Load testing microservices and identifying scalability issues — Engineering Fitness</a> was originally published in <a href="https://medium.com/fitbit-tech-blog">Fitbit 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[Bugcrowd and Fitbit partner to launch public security bug bounty program]]></title>
            <link>https://medium.com/fitbit-tech-blog/bugcrowd-and-fitbit-partner-to-launch-public-security-bug-bounty-program-478d510888c9?source=rss----71d55fdd6fe---4</link>
            <guid isPermaLink="false">https://medium.com/p/478d510888c9</guid>
            <category><![CDATA[fitbit]]></category>
            <category><![CDATA[wearables]]></category>
            <category><![CDATA[bugcrowd]]></category>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Fitbit Eng Blog Editor]]></dc:creator>
            <pubDate>Wed, 11 Sep 2019 17:11:09 GMT</pubDate>
            <atom:updated>2019-09-11T17:11:08.942Z</atom:updated>
            <content:encoded><![CDATA[<p>Fitbit has always been committed to protecting consumer privacy and keeping data safe. Our internal security team is constantly testing our products for vulnerabilities as we strive to continuously strengthen our security. And, as our devices become more and more complex, we we are more mindful than ever that weaknesses can be difficult to identify. That’s why Fitbit has been partnering with Bugcrowd — a crowdsourced security solution. Bugcrowd utilizes a global team of security researchers to help companies discover and remediate software vulnerabilities.</p><p>And today we’re extending our security bug bounty program to include a paid, public program.</p><p>Through Bugcrowd’s platform, security researchers from all over the world can test our software and devices. To thank researchers for their time and effort in discovering security issues, we will offer financial rewards (between the range of US$100 — US$2500) for any valid, non-duplicate submissions.</p><p>The expansion to our bug bounty program is a natural progression of the success we have experienced working with Bugcrowd in the past. We started our journey by initially offering a public “kudos” program — rewarding researchers with recognition and a thank you from us when they’ve helped in identifying a security issue. Shortly after, we decided to venture into paid bounties with a private program. To date, we have rewarded over $60,000 to researchers with an average payout of $600 per submission.</p><p>The addition of a public, reward-based program complements our internal security assurance and testing capability. Increasing the interest of security researchers to our program allows us to extend the size of our security team; there are over 60,000 researchers on the Bugcrowd platform. The use of Bug Crowd enables Fitbit to have a depth and breath of security testing at an unprecedented scale.</p><p>Security at this scale means that vulnerabilities are discovered even faster and in some very innovative ways. Adding our newest hardware devices to the program, including the Fitbit Ionic smartwatch and Aria 2 scale, also offer an interesting landscape for researchers to test on. To date, we have had around 400 researchers who have submitted findings to us. We look forward to collaborating even more with the security research community and are proud to help lead the industry with this standard of security engagement.</p><p>If you are interested in checking out the program or participating, please head over to our page on <a href="https://fitbit.com/bugbounty">Bugcrowd</a>.</p><p><em>Originally published at </em><a href="https://eng.fitbit.com/bugcrowd-fitbit-partner-launch-public-security-bug-bounty-program/"><em>https://eng.fitbit.com</em></a><em> on February 14, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=478d510888c9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fitbit-tech-blog/bugcrowd-and-fitbit-partner-to-launch-public-security-bug-bounty-program-478d510888c9">Bugcrowd and Fitbit partner to launch public security bug bounty program</a> was originally published in <a href="https://medium.com/fitbit-tech-blog">Fitbit 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[Evaluating Google Cloud Spanner and BigTable — Engineering Fitness]]></title>
            <link>https://medium.com/fitbit-tech-blog/evaluating-google-cloud-spanner-and-bigtable-engineering-fitness-a4c2135b1c70?source=rss----71d55fdd6fe---4</link>
            <guid isPermaLink="false">https://medium.com/p/a4c2135b1c70</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[time-series-database]]></category>
            <category><![CDATA[sharding]]></category>
            <category><![CDATA[spanner]]></category>
            <category><![CDATA[big-table]]></category>
            <dc:creator><![CDATA[Fitbit Eng Blog Editor]]></dc:creator>
            <pubDate>Wed, 11 Sep 2019 17:06:11 GMT</pubDate>
            <atom:updated>2019-09-11T17:06:18.761Z</atom:updated>
            <content:encoded><![CDATA[<h3>Evaluating Google Cloud Spanner and BigTable</h3><p>As one can imagine, the millions of active Fitbit users generate a lot of data. All that data has to be processed and stored so that users can look back on historical step counts, sleep, etc. One such storage service that I focused on as an intern on the Data Storage team, is the Device Communication Log (DCL) service. The messages sent through the DCL service contain everything the tracker collects, including user activity data and tracker state. DCL data is currently stored in a sharded MySQL database. While the relational nature of MySQL makes queries straightforward, the Data Storage team dedicates a fair amount of time to the maintenance of our <a href="https://en.wikipedia.org/wiki/Shard_(database_architecture)">sharding</a> infrastructure to scale MySQL for our needs.</p><h3>Overview of DCL</h3><p>Any storage solution for DCL has to support common read and write operations our apps need:</p><ol><li>Saving a sync entry to the database</li><li>Reading a sync entry based on a unique log entry ID</li><li>Reading sync entries for a given user/device in a time window</li><li>Deleting all sync entries for the user/device</li></ol><p>The DCL workflow is write-heavy: once data is written to the database, it isn’t often read. When it is read, it is often the most recent data.</p><h3>Spanner and BigTable</h3><p>With Fitbit moving it’s infrastructure to the Google Cloud Platform (GCP), I evaluated two Google Cloud stores, <a href="https://cloud.google.com/spanner/">Spanner</a> and <a href="https://cloud.google.com/bigtable/">BigTable</a> as alternatives to MySQL. Spanner and BigTable are fully managed services, with routing and sharding handled internally. Spanner is a scalable relational database service with transactional consistency, SQL query support, and secondary indexes. BigTable is a scalable NoSQL database. Other options within GCP such as Cloud SQL and Cloud Storage weren’t evaluated.</p><p>When designing our schema, we wanted to avoid write hotspots, and large table scans for reads. User IDs and Device IDs are generated in monotonically increasing order, and it is reasonable to think that newer users sync more often, contributing to more traffic.</p><p>Our Spanner model has a single table with {reversed device ID, unique log entry id} as the primary key. The device ID is reversed to avoid hotspots. It has two secondary indexes — One on {reversed user ID, creation time}, and the other on {reversed device ID, creation time}.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*nNe6Y0p_8rW8zBr_.png" /><figcaption>Figure 1: Spanner table</figcaption></figure><p>We modeled data in BigTable in two ways — what we call “BigTable Tall” and “BigTable Versions”.</p><p><em>BigTable Tall</em></p><p>BigTable Tall has a main table with the row key {reversed device ID # timestamp # log entry ID}.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*53NUBNw0ZHcZyL4g.png" /><figcaption>Figure 2: BigTable Tall : Main table</figcaption></figure><p>We also created a second table for lookups by user id. This table only held a reference to the device id, so, each query to this table would then lead to a second query on the main table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*QR_8Pam2ASbgvpK1.png" /><figcaption>Figure 3: BigTable Tall : User ID lookup table</figcaption></figure><p><em>BigTable Versions</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*lIFO_uaIxlTc-GgF.png" /><figcaption>Figure 4: BigTable Versions : Main table</figcaption></figure><p>This model treats each sync entry as a different “version” of data for a device. The row key in the main table is simply the reversed device ID. Similar to BigTable Tall, there is a second User ID-based lookup table.</p><p>Performance and Cost</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*wIAQUyeO7AXf6czw.png" /><figcaption>Figure 5: 99th percentile latency for each operation</figcaption></figure><p>Performance testing was done by running JMeter scripts remotely on GCE instances in the same Google Cloud region as the databases (to minimize network latency). Performance testing was only completed against the Spanner and BigTable implementations, while comparable tests against the current MySQL setup were in progress.</p><p>As figure 5 shows, BigTable Versions performed poorly on p99 latency for reads by user ID. BigTable doesn’t seem to be efficiently retrieving a specific version/timestamp here. Spanner outperformed both BigTable implementations significantly for getting an entry by device ID and log entry ID, because this is a row lookup on the primary key. BigTable requires a scan of all rows for a device. A possible improvement (at the cost of more storage) is to make the row key of the main table similar to Spanner’s primary key and create two secondary tables allowing for lookups based on device and user ID.</p><p>To estimate cost, I determined how much the “reported” size of the data would differ from MySQL. Both Spanner and BigTable store data in Colossus, which uses Reed-Solomon error correction to improve fault tolerance and adds to storage space. I found that for each GB of data in MySQL, the data would take 1.5 GB in Spanner and 1.2 GB in BigTable. Taking this into consideration, I found that for our storage needs, Spanner would be 25% less expensive, and either BigTable approach would be 30% less expensive than our current MySQL setup.</p><h3>Conclusions</h3><p>Our general takeaway is that a BigTable implementation might be best for performance-sensitive services that have simple lookups or can tolerate data being potentially inconsistent across tables. Spanner may perform slightly worse and cost more than BigTable but will provide strong consistency and be easy to reason about. Either would cut costs compared to our current MySQL setup. Most importantly, using one of these storage systems would make services easier to maintain, allowing us to focus on business critical work instead of maintaining MySQL shards.</p><h3>The Internship Experience</h3><p>Coming into this summer, my knowledge of data storage was fairly limited. I could give a textbook definition of ACID transactions, but didn’t know how these concepts applied to real production systems. Needless to say, I got hands-on experience around storing data effectively. I learned that knowing things is helpful: having taken a class that covered databases allowed me to dive deeper into my project because I didn’t first have to learn the basics. But I also learned, perhaps more importantly, that not knowing things is fine too. On that note, I would like to thank my mentor, Devika Karnik; my manager, Bryce Yan; and the rest of the Data Storage team for answering all my questions and being so welcoming this summer! I learned a lot, but the true highlight was getting to know all the wonderful people I worked with.</p><h3>About the Author</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*0jVyHCRyqzKWOg-X.jpg" /><figcaption>Josh Rosenkranz</figcaption></figure><p>Josh Rosenkranz is currently a senior at MIT. He is a member of the class of 2019 studying Computer Science and Electrical Engineering. Josh is also the cross country team captain in the varsity Cross Country and Track and Field team at MIT. His interests in running and computer science made perfect sense for him to spend his summer in 2018 as an intern in the Data Storage team at Fitbit. While spending time working on his internship project, Josh also won the 5K race at the 2018 San Francisco Marathon.</p><p><em>Originally published at </em><a href="https://eng.fitbit.com/evaluating-google-cloud-spanner-bigtable/"><em>https://eng.fitbit.com</em></a><em> on December 17, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4c2135b1c70" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fitbit-tech-blog/evaluating-google-cloud-spanner-and-bigtable-engineering-fitness-a4c2135b1c70">Evaluating Google Cloud Spanner and BigTable — Engineering Fitness</a> was originally published in <a href="https://medium.com/fitbit-tech-blog">Fitbit 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[What is Bitgatt and why do we need it?]]></title>
            <link>https://medium.com/fitbit-tech-blog/what-is-bitgatt-and-why-do-we-need-it-b884ba2ebf6d?source=rss----71d55fdd6fe---4</link>
            <guid isPermaLink="false">https://medium.com/p/b884ba2ebf6d</guid>
            <category><![CDATA[bluetooth-low-energy]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[bluetooth]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[fitbit]]></category>
            <dc:creator><![CDATA[Irvin Owens Jr]]></dc:creator>
            <pubDate>Tue, 10 Sep 2019 19:12:17 GMT</pubDate>
            <atom:updated>2019-09-10T19:12:17.070Z</atom:updated>
            <content:encoded><![CDATA[<p>At Fitbit we utilize Bluetooth Low Energy, commonly known as BLE, for particularly heavy data transfers which are more complex than the common handful of use-cases for this extremely efficient radio technology. One of the perks of the job, in my opinion, is to try to deliver amazing experiences between wearables and cloud-connected mobile devices through the heavy use of the various BLE technologies and specifications. Unfortunately one of the side-effects of this is that we find ourselves living in edge cases that Android OEMs, and sometimes even Google, didn’t anticipate when designing their APIs and implementing their bluetooth drivers. We presently make limited or no use of standard bluetooth GATT profiles for low energy because there aren’t any that are sufficient for the variety of functionality we desire from our wearables. Because of this we have designed our own protocols to perform the operations that are required for our devices to help you reach your health and fitness goals and to provide a robust app ecosystem.</p><p>The Android BLE API, at present, roughly mirrors the Broadcom developer API used for their chipsets abstracted by means of an open source Linux library called “bluedroid” with significant modifications, all contributed back by Google naturally, then bridged using JNI for Java. There are a number of adjustments to ensure some level of security and isolation between applications, but aside from that it represents a fairly raw API giving developers an amazing amount of power, but at the same time limiting access in ways that are often frustrating. In some ways this is the worst of both worlds, you have the power to shoot yourself in the foot constantly, but not enough power to actually resolve the issues that your use of the API as documented will create. Bluetooth as you can see below is an incredibly complex layer-cake of protocols and requirements which are very easy to miss, skip, or hack for OEMs who are under time pressure to deliver these complex radio devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OB7GfXrYITNG1K5X" /><figcaption>So you can see why this is hard…</figcaption></figure><p>We have refactored our Bluetooth implementations several times in the past at different levels over the years as we gained more knowledge of what was actually transpiring down in the Android OS stack and even below in the OEM’s BSP stack. What we found was that there is quite a wide variance of behaviors between Android OS versions, phone models, Bluetooth chipset vendors, and even cellular carriers. For example, on some models of Android handset the antenna design is such that when Wi-Fi and Bluetooth are both active there is a non-trivial bit of compromise on the performance of Bluetooth as regards throughput. This creates issues for us as we transfer megabytes of data over this channel at times. The user may be using many different BLE and Bluetooth devices using any one of the available protocols at any time. The Android API does not give feedback to the developer regarding the users’ use of Bluetooth on the phone, so it is up to their code to infer what is happening in the environment and react. This is just one of the complexities of being a mobile Bluetooth developer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*nNX-q7gqYzybqjfP" /><figcaption>Bluetooth all the things! Image by <a href="https://pixabay.com/users/200degrees-2051452/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1690677">200 Degrees</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1690677">Pixabay</a></figcaption></figure><p>Several years ago, when we didn’t fully understand how these various inconsistencies could conspire to create odd bugs, it would take us months sometimes to troubleshoot bugs after reading thousands of lines of logs and doing that across dozens of handsets. We would try to reproduce a bug encountered on a lower-end device on our developer spec flagship Android handset and fail to reproduce it. These issues led us to simplify our code, reducing threading, caching and other complexities in an effort to make troubleshooting easier. This helped, but we still had odd issues that we couldn’t explain reviewing our code alone. At this point, as the mobile team, we had enough knowledge of BLE as a spec, our tracker firmware, and the various chipsets’ drivers to start to triangulate the issue. More often than not, it would result in a complex interaction bug where the chipset driver implementation either fails to comply with the BLE specification, or creates an adverse interaction between the particular version of Android and that chipset implementation, leading to paralysis of the BLE API. When this occurs it is resolvable only by restarting bluetooth (it is still amazing that you can do this without user interaction) or by asking the user to clear their bluetooth share (dropping the GATT databases).</p><p>Some potential solutions we considered were more aggressive, including turning bluetooth on and off automatically, heavily using private methods, etc … We understand however, that for a user who is utilizing Bluetooth for multiple operations on their device this would create a horrible experience for that user, and though it would be difficult for them to know that it was our application causing problems with their headphones, etc … we as Android users would not want an application behaving in this way on our own phones, so we would not do this to our users.</p><p>We determined that the only way forward was to establish a deep understanding of how things were working such that we could work around these problems in the most expedient way. Then we could quickly triage and report other issues to Google, leaving it for them to manage as stewards of the platform. To that end we needed to have a robust understanding of the state of our interaction with the GATT, prioritizing stability over speed.</p><p>In order to quickly find issues we have split our implementation into three tiers. The lowest level was to be around our interactions with the GATT, the middle level to be our protocol implementation, and at the highest level, our business logic. The library that we are now open sourcing is the one around the lowest level, our GATT interaction. We do this in the hopes that we can help other developers avoid some of the pitfalls that we have run into with Android BLE, and to get help adapting to the issues that we can not avoid. This level of encapsulation and separation of concerns allows us to have robust test harnesses even at runtime to verify that as far as that tier of logic is concerned, we are certain that the behavior is logical. This enables us to identify problems with Android or the OEM’s Bluetooth implementation quickly and thus avoid spending precious time trying to fix the unfixable while filing issues against the correct party.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wt1juaHmMsTXnzNV" /><figcaption>Bitgatt system diagram</figcaption></figure><p>What Bitgatt, or Fitbit Gatt, attempts to do is to operate transactions against the GATT database, this database being the repository on both sides of the connection that is synchronized on a schedule and is at the core of the concept of BLE. Bitgatt will provide a single thread per connected peripheral that operates on its own queue to prevent the Android OS’ queue from filling. On several versions of Android if the GATT queue is full when the device disconnects, you will receive, upon connection, the already full GATT queue once again represented by a “client_if” or client interface. When you attempt GATT operations they will go onto the end of this queue and not be able to be sent, because this queue is closed. Managing our own queue is an example of one of the many design choices we made when building Bitgatt that prevent an Android developer from creating their own nightmares when heavily using BLE.</p><p>Another significant issue that Bitgatt seeks to help developers to avoid, is that when writing and notifying quickly on some Android versions, the value provided in the characteristic is a pointer to the C structure holding the data. This means that upon the next write, the value that the Android Java object points to is different than the value that you received initially (not to mention that the GATT callbacks are being delivered on the JNI binder thread which creates its own issues if you have long running operations triggered in the callback). To prevent this Bitgatt does deep copies of the characteristics, services, and descriptors returned. In addition to this, constructing a characteristic or descriptor, writing a value, and then attempting to update or notify this value on a remote device will fail because there is an instance id variable contained in the object provided from the BluetoothGatt object itself. The BluetoothGatt object will actually take one of these constructed data objects and then become stuck, instead of rejecting the instance. Bitgatt uses its own object types for characteristics, descriptors, and services to prevent this possibility. There are dozens of other issues that Bitgatt will protect potential implementers from, however those are a couple of the most insidious.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*itlAb1xEYFVlPIg5" /><figcaption>Strategy Pattern</figcaption></figure><p>For issues that arise that are specific to phone models, we have employed the strategy pattern. This is to prevent compromising the core of the implementation with model / OS / Carrier specific hacks that will render it unmanageable in the future. Removing these strategies is fairly straightforward as there are clear hooks where we employ the strategy. Once the device that has the specific issue is no longer a concern, the code can be deprecated and removed without a full set of regression tests.</p><p>Finally, we have built a lab environment in which we can test the GATT implementation of the phone independently of any Fitbit business logic (outside of Bitgatt). We can simulate any tracker’s behavior and determine whether the mobile OS or our firmware behavior is at fault. We run automated regressions against Bitgatt, but we also try to test when mobile OS updates roll out to help us detect issues hopefully before our users. There is probably another entire blog post on our testing around GATT, but I’ll leave that to another developer :-).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*4zms2zMfKddugCZM" /><figcaption>It all started here — BT4.0 … Android phones that use this are still out there …© Raimond Spekking / <a href="https://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0</a> (via Wikimedia Commons)</figcaption></figure><p>Ideally, and perhaps idealistically, as Android BLE has been something of a tragedy of the commons with every application having access to every other application’s peripherals, being able to interact with the radio in unfettered ways, and consuming BLE bandwidth in any way they see fit, working together to utilize one or more quality libraries can help to reduce the bandwidth wasted through un-necessary scanning, applications fighting with each other and keeping the GATT queues healthy. We hope that you find Bitgatt useful, even just for inspiration, and we look forward to collaborating with the Android community on BLE. Even if you are just looking to do something simple with BLE, it would be best to start using one of the existing BLE frameworks, as you will be able to spend more of your time on your own functionality and less troubleshooting someone else’s. Inevitably whatever your use of BLE you will ultimately expand your feature set and eventually find yourself where we were, understanding that this technology is deeply powerful, but also wildly complex. We are still learning, and we hope that you will learn with us.</p><p><a href="https://github.com/fitbit/bitgatt">https://github.com/fitbit/bitgatt</a></p><p>About the Author</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/0*5JBETIEJfh-VQ4-1" /><figcaption>Irvin Owens Jr — Principal Software Engineer.</figcaption></figure><p>Irvin has been working on Android at Fitbit for 4 years and has been focused on Bluetooth Low Energy for the past 3 years. He has worked on everything from backend to full-stack, down to mobile, and embedded. He enjoys cycling around the Bay Area and playing basketball with his family. He is presently training (quaking silently) for an impending ride up Mt. Baldy, but he still may chicken out and settle for a metric century around the East Bay :-).</p><p><em>Originally published at </em><a href="https://eng.fitbit.com/what-is-bitgatt-and-why-do-we-need-it/"><em>https://eng.fitbit.com</em></a><em> on June 4, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b884ba2ebf6d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fitbit-tech-blog/what-is-bitgatt-and-why-do-we-need-it-b884ba2ebf6d">What is Bitgatt and why do we need it?</a> was originally published in <a href="https://medium.com/fitbit-tech-blog">Fitbit Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>