<?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[Qubit Engineering - Medium]]></title>
        <description><![CDATA[Qubit.com’s engineering blog - Medium]]></description>
        <link>https://medium.com/qubit-engineering?source=rss----a1e5a35d34d7---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Qubit Engineering - Medium</title>
            <link>https://medium.com/qubit-engineering?source=rss----a1e5a35d34d7---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 12:32:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/qubit-engineering" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Kubernetes: Up & Integrated — Secrets & Configuration]]></title>
            <link>https://medium.com/qubit-engineering/kubernetes-up-integrated-secrets-configuration-5a15b9f5a6c6?source=rss----a1e5a35d34d7---4</link>
            <guid isPermaLink="false">https://medium.com/p/5a15b9f5a6c6</guid>
            <category><![CDATA[mesos]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[vault]]></category>
            <category><![CDATA[gke]]></category>
            <dc:creator><![CDATA[Tristan Colgate-McFarlane]]></dc:creator>
            <pubDate>Wed, 22 Nov 2017 09:54:51 GMT</pubDate>
            <atom:updated>2017-11-22T09:54:51.389Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the second in a four part <a href="https://medium.com/qubit-engineering/kubernetes-up-integrated-authentication-5d2c908c2810">series</a> on how we at Qubit built our production ready Kubernetes (k8s) environments. For those of us with pre-existing configuration management workflows, moving to k8s can present some challenges. We will briefly describe Qubit’s previous configuration management process, where it caused problems and what we wanted to preserve. After this we will present a detailed overview of the workflow we have built. This will be a long post, you have been warned!</p><p>The tools we will discuss here are not open-source at this time. We hope to release something in the near future. The workflow is also not perfect. We will discuss where the weaknesses lie and how things may change.</p><p>As with the previous article we will assume a reasonable working knowledge of Kubernetes. We will also be discussing some issues involving HashCorp’s <a href="https://www.vaultproject.io/">Vault</a>. We’ll discuss relevant Vault topics briefly but will not attempt to give an exhaustive treatment.</p><h3>The Ghost of Config Past</h3><p>Qubit’s previous configuration management process was built around <a href="https://puppet.com/">Puppet</a> and <a href="https://github.com/voxpupuli/hiera-eyaml">hiera-eyaml</a>. Any configuration containing sensitive material, such as passwords, authentication tokens and private keys, are stored in a central Puppet Git repository. The repository contains a public key that can encrypt data which can than be decrypted by the Puppet master server. Nodes within the cluster infrastructure retrieve configuration from the Puppet master, the master decrypts any encrypted data, passing fully rendered configuration to the cluster node. The container orchestration infrastructure on each node (<a href="http://mesos.apache.org/">Apache Mesos</a>) can then mount the rendered content into containers as they start.</p><p>Many of the workloads running within the clusters are Node.js tasks using the <a href="https://github.com/lorenwest/node-config">node-config</a> package for configuration. We leverage the merging behaviour of both hiera-eyaml and node-config. Applications can ship per-environment settings in e.g. staging.yaml, hiera then merges an unencryped per-application YAML section with the decrypted per-application settings, and renders this into a local.yaml file. The practical result is that developers can place a section of their configuration, as YAML, into our Puppet repository, and have that presented to their application in a secure fashion.</p><p>The developer workflow is as follows:</p><ol><li>Create or update an application’s configuration requirements.</li><li>Create a new section in the Puppet repository with the encrypted version of a secret.</li><li>Raise a pull-request to merge the new configuration section.</li><li>Wait for Puppet to deploy the secrets to the cluster nodes. In our case: one run per-hour per-node.</li><li>Once merged, deploy the new version of the application.</li></ol><p>This process meets many of our security needs:</p><ul><li>Secrets are not checked-in to any source repository in plain text.</li><li>Plain text secrets are at rest in a relatively minimal set of locations (on the root partition of each cluster node).</li><li>Plain text secrets are only visible to the intended recipient application.</li></ul><p>Many of you will have similar workflows. With hindsight and experience it is easy to be critical of this workflow. We’ll discuss the practical problems we experienced, but it is important to state that for many organisations this process is perfectly adequate. Many of the issues we’ll discuss below could be fixed by other means, without moving away from Puppet. We could certainly have stuck to this workflow with our move to k8s, for many people that will certainly be the right thing to do. That being said, here is a brief list of issues we faced regularly:</p><ul><li>Pull-request review by the Infrastructure team becomes a bottleneck for developers.</li><li>Unnoticed errors in configuration easily broke Puppet runs for all applications, and all related infrastructure.</li><li>Feedback on when Puppet has finally deployed configuration to the cluster is very poor and of limited visibility. Either Puppet runs were forced, which required Infrastructure team action, or the developer had to wait for “about an hour” before deploying.</li><li>Deploying an application before Puppet had deployed configuration had unexpected results. Docker creates a local directory if asked to mount a file into a container if no such file exists on disk. This results in Puppet runs failing when a directory exists where a file should have been. This required Infrastructure team involvement to fix. The application would also deploy, but fail when attempting to read a directory.</li></ul><p>As Qubit’s development teams scaled up, occasional irritating misbehaviour turned into serious problems.</p><h3>What Does “Good” Look Like?</h3><p>In the previous section we have discussed some of the practical issues we faced with our Puppet based configuration process. It is worth taking a step back and trying to understand how these issues impacted the Big Picture.</p><ul><li>Developers had to be aware of the behaviour of a tool they would never actually run or use directly (Puppet).</li><li>Developers had to work with an extra code repository.</li><li>The Infrastructure team had to be involved with many new deploys, or emergency deploys, and all secret changes (or any changes to any of the configuration managed by Puppet).</li></ul><p>As mentioned in the previous article in this series, we aim to have development teams have complete ownership of everything needed by their application from one single code repository. Ideally this should include:</p><ul><li>Code, tests and CI configuration.</li><li>Configuration needed for deploying the application.</li><li>Run-time configuration.</li><li>Metrics and alerting configuration.</li></ul><p>It is worth mentioning at this point that Qubit do not (at this time) have what other organisations might call an Operations team (variously known as ‘SRE team’, or the outright oxymoron of ‘DevOps team’). Development teams are responsible for the day-to-day running of their applications. Qubit’s Infrastructure team is focused on building, managing and maintaining the underlying infrastructure and providing the tools for the developers to use that infrastructure. This allows the number of services and associated development teams to scale independently of the Infrastructure team.</p><h3>A Brave New World</h3><p>Kubernetes presented a new challenge. One of our goals was to make deployments agnostic of the underlying cloud provider. We could have built k8s infrastructure via Puppet in both GCE and AWS, we had already done this for Mesos. Our existing Puppet infrastructure would have needed work to support GCE. The presence of GKE made this approach less attractive. <a href="https://github.com/kubernetes/kops">Kops</a> had also provided a straightforward approach to delivering a solid k8s infrastructure on AWS without this effort. The idea of no longer requiring Puppet to build the underlying cluster nodes was too attractive to pass up, especially when combined with the issues presented above.</p><p>The subject of presenting secrets to containers is generally known as Secret Injection. Fortunately for us, people had already outlined approaches to Secret Injection within k8s. Whilst none of the existing tools completely covered our use case, there was enough prior-art to give us a head start.</p><p>We had settled on HashiCorp’s Vault for storage of secrets. Vault is an incredibly powerful tool. While there is a wealth of introductory documentation on Vault, there is considerably less by way of detailed discussion of production ready deployment. All requests to retrieve secrets from Vault require a Vault Token with suitable assigned policies for reading a given secret. Getting an initial token for a service to talk to Vault can seem like a ‘chicken and egg’ situation. Various mechanisms can be used to get an initial Vault token (see Authentication Backends), but the most relevant to our use case all require some other process to already have a Vault Token. This ‘Token Bootstrapping’ represents a real challenge to production Vault deployments.</p><p>Once you have logged in to Vault, you still have to access and use your secrets. We considered requiring developers to talk to Vault directly. This would have been the easiest option for the Infrastructure team, and arguably given the best end result in terms of Vault integration. In reality the code changes required to some 200 micro-services ruled this out. Vault is not an easy tool to use, especially when compared with YAML configuration files loaded via node-conf. Simply retrieving secrets is not the only issue, for some secrets the Vault Token must be periodically refreshed.</p><p>Our final goals were:</p><ul><li>Minimal / No code alteration for existing applications.</li><li>Minimal configuration changes.</li><li>Configuration from the application’s source repository.</li><li>Configuration available immediately upon deployment.</li><li>Minimal exposure of plain text secret content.</li><li>Allow leveraging advanced Vault concepts (such as managed PKI, and managed lifetime secrets for AWS).</li></ul><p>Our eventual approach was inspired by three existing projects:</p><ul><li><a href="https://github.com/kelseyhightower/vault-controller">https://github.com/kelseyhightower/vault-controller</a></li><li><a href="https://github.com/Boostport/kubernetes-vault">https://github.com/Boostport/kubernetes-vault</a></li><li><a href="https://github.com/kelseyhightower/confd">https://github.com/kelseyhightower/confd</a></li></ul><p>Since you have been so patient, and we still have a long road ahead, we’ll break up proceeding with the basic block diagram of what we eventually produced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*Bw6CRX2lJNQ5IEde4QycfA.png" /></figure><h3>Token Bootstrap</h3><p>We elected to use Vault’s <a href="https://www.vaultproject.io/docs/auth/approle.html">AppRole</a> feature. With AppRole a micro-service is assigned to a given AppRole in Vault. A micro-service instance must log in to the Vault AppRole to obtain a Vault Token before it can begin reading secrets. In order to log in to the AppRole, an instance of a micro-service requires two pieces of information:</p><ul><li>AppRole RoleID, by default this is a UUID. There is only one RoleID for a given AppRole.</li><li>AppRole SecretID, a UUID that is retrieved from Vault by another process which is allowed to issue SecretIDs for a given AppRole. In our configuration this SecretID is unique for each new running instance, may only be used to log in to Vault once, and is only valid for a limited time after being issued.</li></ul><p>Getting two pieces of information to our embryonic micro-service instance might seem harder than the problem we originally had of getting a single Vault Token into our container. We seem to have made our situation worse. There is a very good reason for taking this approach. These two bits of information can be delivered by different means, and neither of the processes responsible for either part of that delivery ever have enough information to actually log into the AppRole and retrieve the applications secrets. Our embryonic micro-service instance can combine these two IDs and use them to log into Vault, the resulting token grants it the power to read secrets. Since the SecretID may only be used once we can also detect potential misuse. If a service is unable to log in to Vault with a given RoleID and SecretID then only one of two things could have happened. It either took them too long, or the SecretID has already been used. It is possible, via Vault’s Audit infrastructure, to spot and alert on the latter case.</p><p>This is excellent, but we still have a Token Bootstrapping problem. In order to get the RoleID and SecretIDs for an AppRole, whatever is requesting them must, in turn, have a valid Vault token. In our case, the RoleID will be retrieved by the process that is deploying the application (usually a CI tool or developer laptop), and the SecretID will be retrieved by an in-cluster Vault Controller. We could pick any other Vault <a href="https://www.vaultproject.io/docs/auth/index.html">authentication method</a> here. The RoleID could be retrieved by a user authenticated via the GitHub authentication mechanism, whilst the SecretID process could be authenticated by an EC2 or GCP machine credential.</p><p>There is a further complication here that ruled out these simple authentication methods. Vault Policies are not very dynamic things at present. We want each AppRole to be limited to reading secret for just its associated micro-service. Out of the box Vault would require the developer to be able to create a policy for their application, and create the associated AppRole. This gives the developer carte-blanche as to the content of that policy. Whilst we do trust our developers, this would require them to understand Vault policies and would be very prone to error.</p><p>Since we already have a central authentication mechanism based on JWTs (discussed in our <a href="https://medium.com/qubit-engineering/kubernetes-up-integrated-authentication-5d2c908c2810">previous article</a>), we elected to leverage it. We have built a small Secret API that sits in front of Vault and is responsible for managing AppRoles and policies. The deployment process can request the RoleID for a given application from the Secret API. After verifying the request the Secret API creates a set of policies for the application, along with an AppRole. Similarly, access to SecretIDs is controlled via this service. Pushing these parts of the Vault flow through an API also allows us to use our existing authorisation mechanism based on our internal Google Groups.</p><h3>The End Result</h3><p>Here is a brief overview of each of the components in the diagram above:</p><ul><li>Vault: Stores secrets at rest and enforces access policies.</li><li>SecretAPI: Manages Vault AppRoles and policies, and is responsible for authorising access to Vault AppRole details. It is also used for setting secrets and maintaining a version history of secrets.</li><li>Docker (Init): A Docker Registry containing a set of Init Containers for applications.</li><li>Docker (Apps): A Docker Registry containing the main application containers. This is currently the same registry as the Init registry, this will be discussed further in the Future Work section.</li><li>Secret Controller: Runs within each Kubernetes cluster. This is responsible for retrieving SecretIDs for new Pods.</li><li>Secret Init Container: This is a container added to each Pod needing to receive configuration.</li><li>Secret Refresh Cotainer: Optional container that can be used to manage Vault leases.</li><li>Config Volume: A tmpfs in-memory volume shared between the Init Container and the main Application Container. This stores the final configuration for the application.</li><li>Lease Volume: A tmpfs in-memory volume shared between the Init Container and the Refresh Container. This stores any Vault Leases that will need to be refreshed.</li></ul><p>The final system is probably best described via a worked example. We will describe the key components in the process as they become relevant.</p><p>We will start with an application. We have a source code repository with the following content:</p><pre>/Dockerfile            - to build out final application container<br>/deployer.yml          - our deployment configuration file<br>/config/staging.yml    - non-secret node-config file for staging<br>/config/production.yml - non-secret node-config file for production<br>/config/local.yml.tmpl - Go template that will become local.yml<br>/...                   - the rest of our application code</pre><p>Developers, if so authorised, can set specific secrets within Vault using a command line utility that talks to the Secret API.</p><p>When the application is deployed:</p><ol><li>The main application’s Docker container is built and pushed to the application Docker repository.</li><li>The deployment tool contacts the Secret API to retrieve the RoleID for this application, specifying the destination cluster’s details.</li><li>If the user running the deployment is suitably authorised the Secret API server ensures the necessary Vault AppRole and policies exists and returns the RoleID and AppRole name to the user.</li></ol><h4>The Vault AppRoles and Policies</h4><p>When an application is first deployed we create four items in Vault. First we create the AppRole itself. This controls the set of permissions that will be given to the final Pod that retrieves the information. An example might be as follows:</p><pre>auth/approle/role/aws.stg.myapp</pre><pre>period                  300<br>policies                [default secret-api/read-aws.stg.myapp]<br>secret_id_num_uses      1<br>secret_id_ttl           300<br>token_max_ttl           300<br>token_num_uses          0<br>token_ttl               300</pre><p>This is an AppRole for instances of myapp running in the stg (staging) cluster within aws (Amazon Web Services). The tokens issued to the final application will be refreshable tokens and will be given the secret-api/read-aws.stg.myapppolicy. We also create that policy:</p><pre>policy secret-api/read-aws.stg.myapp:</pre><pre>path &quot;secret/myapp/*&quot; { capabilities = [&quot;read&quot;, &quot;list&quot;] }<br>path &quot;secret/global/*&quot; { capabilities = [&quot;read&quot;, &quot;list&quot;] }<br>path &quot;secret/project/aws/*&quot; { capabilities = [&quot;read&quot;, &quot;list&quot;] }<br>path &quot;secret/cluster/aws/stg/*&quot; { capabilities = [&quot;read&quot;, &quot;list&quot;] }<br>path &quot;pki/cluster/stg/*&quot; { capabilities = [&quot;read&quot;, &quot;list&quot;] }<br>path &quot;pki/cluster/aws/stg/issue&quot; { capabilities = [&quot;create&quot;, &quot;update&quot;] }<br>path &quot;aws/creds/aws.stg.myapp&quot; { capabilities = [&quot;read&quot;, &quot;list&quot;] }</pre><p>This policy allows the application to:</p><ul><li>read and list various static secrets, some specific to it, others shared among applications</li><li>read and create certificates in a cluster wide PKI</li><li>create AWS credentials specific to this applications role. These credentials are limited to the lifetime of the application.</li></ul><p>We also create a second policy. This will be used by the Secret Contoller later on in the process.</p><pre>policy secret-api/getsecretid-aws.stg.myapp:</pre><pre>path &quot;auth/approle/role/aws.stg.myapp/secret-id&quot; {<br>                capabilities = [&quot;create&quot;, &quot;update&quot;]<br>        }</pre><p>We also create a Vault Token Role (this is separate from an AppRole), associated with this policy:</p><pre>auth/token/roles/getsecretid-aws.stg.myapp</pre><pre>allowed_policies        [secret-api/getsecretid-aws.stg.myapp]<br>disallowed_policies     [root]<br>explicit_max_ttl        0<br>name                    getsecretid-aws.stg.myapp<br>orphan                  false<br>path_suffix        <br>period                  0<br>renewable               true</pre><p>We will explain this policy briefly when we get to the Secret Contoller.</p><p>We continue with our deployment:</p><p>5. The deployment tool takes the AppRole information returned in the previous step and builds an InitContainer that will be added to the Pod.</p><h4>The Init Container</h4><p>Kubernetes allows Pods to have Init Containers. These containers are run before other in the Pod. They must run, and finally exit cleanly before the Pod start-up is allowed to continue.</p><p>Our Init Container includes 3 things:</p><ul><li>A binary capable of logging in to a Vault AppRole, and rendering Go Template files that include secret lookups into Vault.</li><li>The AppRole RoleID information. This is the first half of our AppRole login details.</li><li>The set of configuration files from the /config directory of the original source code.</li></ul><p>Once the Init Container is pushed to the Docker registry, the deployment continues:</p><p>6. The deployment tool creates a set of k8s Deployments in the cluster. The deployments include the Vault AppRole name as an annotation on any Pod specification that wishes to engage in the Configuration process.</p><p>7. Kubernetes starts a Pod.</p><p>8. The Init Container starts. After reading in the RoleID information it begins listening on a known port.</p><p>9. The Secret Controller watches for new Pods. Upon finding one with suitable annotations, and with a running InitContainer listening on the known port, it begins its work.</p><h4>The Secret Controller</h4><p>The secret controller runs in each cluster. It has a Google Cloud Service Account specific to that cluster which permits it to retrieve SecretIDs on behalf of applications started in that cluster.</p><p>When it finds a new Pod wanting configuration, it contacts the SecretAPI and asks for a Vault Token for reading SecretIDs for the given application. Once the SecretAPI approves this request, a new Vault token with the secret-api/getsecretid-aws.stg.myapp policy is issued (via the previously mentioned Token Role). The Secret Controller then contacts Vault directly and retrieves a new SecretID for the required AppRole. This is then passed to the waiting Init Container via a HTTP POST. Ideally this would be a HTTPS POST, however bootstrapping a certificate here is tricky. Since the SecretID is of no use without the RoleID, and we can detect abuse of leaked SecretIDs, we do not consider this to be a major issue. Potentially the forthcoming <a href="https://istio.io/">Istio</a> project could help here, or the Kubernetes Certificate API could be used.</p><p>The Secret Controller’s work is now done, and the deployment of the Pod continues inside the Init Container.</p><p>10. The Init Container now has the AppRole RoleID that was baked into the container image and the SecretID that has been given to it by the Controller. It proceeds to log in to the Vault AppRole. All things being well, it will receive a Vault Token with the secret-api/read-aws.stg.myapp policy mentioned above.</p><p>11. The Init Container now copies any files in the configuration data baked into its image into the shared configuration volume. During this process any file with a .tmpl extension is assumed to be a <a href="https://golang.org/pkg/text/template/">Go Template</a>. The template handling code contains a rich set of functions (including the <a href="https://github.com/Masterminds/sprig">Sprig</a>). Several functions are included for interacting with Vault. The following is an illustrative subset:</p><ul><li>lookup: This looks up a given secret name in the application specific area of the Vault tree for this application.</li><li>awsCredsEnvVars: Retrieves a set of AWS credentials for this process and renders them as sh shell environment variables.</li><li>dbUsername,dbPassword: These can be used to request database credentials from Vault.</li><li>tlsKey, tlsCert , tlsCA: These generate a TLS key and certificate that can be used for mutual authentication within the cluster. The certificates are long lived and a largely intended for providing TLS to any loadbalancer ingress.</li><li>rawRead, rawWrite: These permit arbitrary reads/writes to Vault paths. Since the policy limits the application to specific paths, allowing arbitrary read/write is fine.</li></ul><p>After template rendering the resulting content is written to the shared configuration directory (with the .tmpl extension stripped). The end result is a set of complete configuration files with the relevant secrets for this application, stored on a temporary filesystem readable by the main application container.</p><p>The db* and aws* functions are worth a little further comment. It is important to note here that the credentials the application will get are specific to this running instance of the application and are not shared with other instances. When the application exits these credentials are revoked and destroyed. The creation of these credentials is audited by Vault. We can, for instance, track an action in AWS down to a specific running instance of an application. A practical upshot of this is that AWS and Database credential management is significantly simplified. We no longer need to roll keys. This can be trivially achieved by a rolling restart of the application (or a fresh deployment).</p><p>The final act of our Init Container relates to these temporary credentials. If requested, the Init Container will additionally write the Token and Lease information for any per-process credentials into a second temporary filesystem.</p><p>If all goes well, our Init Container exits cleanly and our deployment continues. If it does not (due to missing secrets, unavailable Vault server, or general network flakiness), the Init Container will eventually be restarted and the process will continue again from Step 8. We shall continue on, assuming all is well:</p><p>12. At this point our main application container starts. It can read its configuration from the shared configuration volume, access required services and begin its work. In the basic case we are now done. If we are using credentials we are leasing from Vault, one further action is required.</p><p>13. Our Kubernetes Pod may include a Secret Refresh Sidecar. If so, it will be started alongside our main application container. It will periodically refresh our Vault token, ensuring that our per application credentials are kept valid. Upon termination it will revoke the Vault token, thus destroying any associated credentials.</p><h3>Profit!…</h3><p>Our application is successfully deployed. Our secrets are in in-memory storage, only visible to the application we desired to have them. Each component on the way has had minimal access to secret related material. By generating temporary per-process credentials we have also achieved something that would be considerably harder to achieve with our original Puppet configuration.</p><h3>Loss?</h3><p>It would be dishonest not to point out some of the weak points in this process:</p><ul><li>The Secret API has considerable access to Vault. Vault has no support for subclassing or templating of policies at this time, so I consider this largely unavoidable unless you are willing to have an Operations team that can take responsibility for create the required Vault elements.</li><li>None of this plays particularly well with Kubernetes Secrets or ConfigMaps. This is less of a problem for internal services, where we generate the k8s objects ourselves, but becomes more awkward when leveraging 3rd party helm charts.</li><li>Config from environment variables is still possible but cannot be configured on the container. A shell must be present inside the container, and suitable shell content rendered to populate the environment. Since this limits visibility of the environment variables from outside the Pod, this can be seen as a reasonable trade-off.</li><li>The Refresh Sidecar needs further work. Kubernetes will not destroy a Pod if an individual Sidecar crashes. Since the crashing sidecar may have revoked the Vault token, we really need to destroy the entire Pod and start again. This could be done from the Secret Controller. Further experience needs to be gathered.</li><li>Kubernetes secrets are still very much a work in progress. Vault integration is on the horizon and it is quite possible that much of this process will be rendered irrelevant in the next 6 months.</li><li>Clearly this process is non-trivial. In reality the volume of code amounts to no more than about 1000 lines spread over 4 processes (the Secret API, Init Container, Refresh Container and Controller). We believe that the end-user experience is no more complicated than the original tooling (with the possible exception of the Go Templates). Time will tell.</li></ul><h3>Future Work</h3><p>We are fairly comfortable with the flow as is. It has proved very reliable and adaptable. The delay on container start imposed by the Init Container is quite minimal, usually dwarfed by the time to download the main container. A typical Init Container run time is in the order of 1 or 2 seconds.</p><p>One area for potential enhancement is the build of the Init Container. The deployer in the above process builds the Init Container and pushes it to a common Docker Registry. The content of the container is just the configuration files and templates that they already have access to. However, they do not strictly need the RoleID. One option we are considering is the have the SecretAPI actually build the Init Container and pass back an image name that can then be included in the Pod. If the Docker Init Registry is only readable by the target k8s cluster, and writable by the Secret API, then the RoleID would never be readable by the process deploying the Pod. Whilst the RoleID does not present a major attack vector, minimising access to it seems like a reasonable option.</p><h3>Conclusion</h3><p>If you have gotten this far, then we thank you for taking the time to read this and hope it has been informative. Kubernetes and Vault are excellent tools and can work together well, but proper integration is a non-trivial task.</p><p>We hope to release the bulk of the tooling used by the process in the following months. Similar, simpler, tools already exist and may be suitable for simpler requirements. Much of the design has been motivated by our multi-cluster configuration and should probably be avoided if you have that option. Ultimately we hope that this post, and the others to follow will be useful in discussing some of the more difficult aspects of production Kubernetes use, and help feed into more general solution that can benefit the whole community.</p><p><em>If you fancy tackling engineering challenges like this, check out the </em><a href="http://www.qubit.com/careers"><em>Qubit careers page</em></a><em> — we are hiring in a wide variety roles and locations.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a15b9f5a6c6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/qubit-engineering/kubernetes-up-integrated-secrets-configuration-5a15b9f5a6c6">Kubernetes: Up &amp; Integrated — Secrets &amp; Configuration</a> was originally published in <a href="https://medium.com/qubit-engineering">Qubit Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes: Up & Integrated — Authentication]]></title>
            <link>https://medium.com/qubit-engineering/kubernetes-up-integrated-authentication-5d2c908c2810?source=rss----a1e5a35d34d7---4</link>
            <guid isPermaLink="false">https://medium.com/p/5d2c908c2810</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[gke]]></category>
            <category><![CDATA[helm]]></category>
            <category><![CDATA[google-cloud]]></category>
            <dc:creator><![CDATA[Tristan Colgate-McFarlane]]></dc:creator>
            <pubDate>Mon, 30 Oct 2017 09:22:21 GMT</pubDate>
            <atom:updated>2017-10-30T10:11:28.381Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the first in a four part series on how Qubit have built our production ready Kubernetes (k8s) environments. There are already many excellent tutorials on k8s. The title of these articles is an homage to <a href="http://shop.oreilly.com/product/0636920043874.do">Kubernetes Up and Running</a>, the (presumably excellent) k8s guide by Brendan Burns, Kelsey Hightower and Joe Beda. In these articles, we hope to cover the more advanced techniques we required to make k8s work at “<a href="https://www.youtube.com/watch?v=iFR_7AKkJFU">modern enterprise</a>” scale.</p><p>We hope to cover:</p><ul><li>Authentication and RBAC across multiple cloud providers.</li><li>Secret and configuration management, replacing Puppet with HashiCorp’s Vault.</li><li>Ingress, DNS, and migration strategies.</li><li>Observability.</li></ul><p>On the way we will briefly mention how the features map to our preexisting tools and policies, and how k8s has helped us build on them. Code samples will be provided where possible, and we do hope to open source more of our tooling in future. I will not hide the warts in our deploy, or the gaps in the tooling. The goal is to present a realistic picture of the reality of a Kubernetes deployment at scale.</p><h3>Becoming Cloud Agnostic</h3><p>Qubit have been early adopters of Cloud, PaaS, and container deployments. We have built features on everything from on-prem Hadoop, AWS Lambda and RDS, to Google Cloud Platform BigQuery and Dataflow. The on-prem and VM deploys were traditionally managed by Puppet, and our micro-services were either deployed directly to VMs, or via containers to Mesos/Marathon clusters hosted in AWS. As GKE appeared some teams began to take advantage of it leading to a split, with some internal tooling focused on Marathon, and various ad hoc deploys on GKE.</p><p>Since our micro-services require access to PaaS services from a variety of cloud providers, we wanted a deployment mechanism that was the same regardless of the actual underlying cloud provider. This allows us to co-locate services with their dependencies, simplifying access to PaaS services and minimising cross cloud data transfer and latency. A common deployment method also allows us to be more responsive to changes in contracts/costs as cloud provider offerings change.</p><p>As k8s development progressed it became a more obvious choice for a single platform to target. GKE had largely solved the problem of how to deploy k8s to Google Cloud (not without its own issues as we shall discuss later). After a review of the options for AWS k8s deploys we eventually settled on <a href="https://github.com/kubernetes/kops">kops</a>. Kops allows multi-master, multi-AZ cluster setup, and management of multiple instance groups. Kops VM base images are well maintained allowing us to avoid Puppet management of the underlying VMs. Kops updates, and rolling updates (especially with KOPS_FEATURE_FAGS=&quot;+DraingAndValidateRollingUpdate&quot;), actually seem to behave better than the GKE equivalent (where the master can frequently become unresponsive during updates).</p><h3>Kubernetes Authentication Webhooks</h3><p>Kubernetes Role Based Access Control (RBAC) was in its early stages during the beginning of our exploration of production k8s. Our initial attempts at GKE avoided the subject completely, but it was obvious from Day 1 that building larger, more efficient, multi-tenant clusters was going to require RBAC. If you are going to use RBAC you need to be know who is using the cluster. This is where Authentication comes in.</p><p>For GKE we disable all legacy authentication, enable RBAC, and enable IAM authentication. This is easy, but does have its limits. In particular, the permissions that can be granted are at a much coarser level than we would like. We’ll discuss this further when we come to our RBAC configuration.</p><p>Enabling RBAC on a kops cluster is easy enough, simply edit the cluster, update authorization to rbac: {}, and roll out the changes. At this time integrating authentication is not quite as smooth.</p><p>K8s API Server has support for authenticating users via a handful of options:</p><ul><li>File of static usernames/passwords for use via Basic Authentication to the API. These are convenient for bootstrapping, and could work for small teams, but would require configuration management, and would not integrate with an external auth provider.</li><li>File of static tokens. As above.</li><li>Certificates signed by the k8s CA. It is possible to integrate this with HashiCorp’s Vault, but that complicates the kops bootstrapping process. Vault did not support GCP authentication at the time, the option is now there so this may be a more practical solution, though support for verifying users Group Membership may not be easy/possible.</li><li>A webhook for verifying bearer tokens presented to the API.</li></ul><p>For our AWS clusters, the webhook was the obvious choice. The manner of configuration is somewhat awkward. A kubectlstyle configuration file must be placed on each master, the content is as follows.</p><pre>clusters:<br>  - name: authn-api<br>    cluster:<br>      certificate-authority: /etc/ssl/certs/ca-certificates.crt<br>      server: <a href="https://authn-api/oauth2/k8sTokenReview">https://authn-api/oauth2/k8sTokenReview</a></pre><pre>users:<br>  - name: authn-api</pre><pre>current-context: webhook<br>contexts:<br>- context:<br>    cluster: auth-api<br>    user: authn-api<br>  name: webhook</pre><p>The kops definition must also be updated:</p><pre>spec:<br>  kubeAPIServer:<br>    authenticationTokenWebhookCacheTtl: 2m0s<br>    authenticationTokenWebhookConfigFile: /srv/kubernetes/authn-webhook.yaml</pre><p>Unfortunately, there is no current way to set the content of the yaml webhook directly in the kops definition. This means that it must be copied to the server at a known path on each master. Stateful drives are mounted at different locations on each machine, and other storage is recreated when masters are updated. This means that when the masters are updated the file must be copied back up to the known location. Solutions for this are in the works, and there may be other options that your author has not considered. Master updates are not so frequent that this has become a major problem.</p><h3>Authentication: Tokens Everywhere</h3><p>We rely on Google’s G Suite for e-mail and much of our documentation, so basing our primary authentication on our Google G Suite credentials has always been the obvious choice. Service Accounts provide a means for us authenticate between micro-services. Google’s own APIs for JWT signing and authentication do not include Google Group membership, and only provide Authorization features for Google’s own APIs and products. For this reason Qubit have an internal service for signing JWTs, and performing OAuth 2.0 flows. Ours is a relatively simple service, <a href="https://github.com/coreos/dex">CoreOS Dex</a> would be the obvious choice for anyone starting out today.</p><p>Integrating our existing JWT token authentication with k8s has been a fun and refreshingly easy experience. The webhook request and response format can be found in the k8s <a href="https://kubernetes.io/docs/admin/authentication/#webhook-token-authentication">documentation</a>, and our implementation is simply a matter of verifying the passed in JWT token, and breaking out the groups from the JWT claim fields. The process is entirely stateless and could actually be run as a small service within the cluster. The process is not particularly latency sensitive, so we actually have the token verification endpoint on our token issuing/signing service.</p><p>The most pleasant aspect of the integration comes from an, almost hidden, feature of kubectl. If you already use GKE with IAM authentication, and happen to look in your .kube/config<em>, </em>you will see something like the following in the users: section.</p><pre>users:<br>- name: gke_project_us-central1-mycluster<br>  user:<br>    auth-provider:<br>      config:<br>        access-token: ya4......<br>        cmd-args: config config-helper --format=json<br>        cmd-path: /home/joe/google-cloud-sdk/bin/gcloud<br>        expiry: 2017-09-13 15:01:44<br>        expiry-key: &#39;{.credential.token_expiry}&#39;<br>        token-key: &#39;{.credential.access_token}&#39;<br>      name: gcp</pre><p>The <em>access-token</em> and <em>expiry</em> are cached values. The interesting part is the cmd-args and cmd-path. If <em>name</em> is set to “gcp”, kubectl will take credentials from the output of executing the given command. The output is treated as JSON, and the <em>-key</em> fields are JsonPath query expressions into the resulting data.</p><p>If we are devious enough to pretend, for a moment, that “gcp” does not have to stand for Google Cloud Platform, but could be General Cloudy Provider, we can leverage this for our own ends. At Qubit we already have a CLI tool used by our developers for various deployment tasks. It was a simple task to add an extra command to this to allow the issuing of a JWT token. When run, the standard OAuth 2.0 browser flow occurs, and all being well, a signed JWT is retrieved from our API server and dumped out in a sufficient compatible JSON format.</p><p>The end result is that a simple kubectl get podscommand will:</p><ol><li>Run our CLI tool to get a token.</li><li>Verify the user via OAuth.</li><li>Cache the token in kubectl.</li><li>Pass this token, which includes the users groups, as the API token.</li><li>The Authn API server calls the webhook to verify the token.</li><li>The Authn API server verifies the token and informs k8s of the user’s group membership.</li></ol><h3>Role Based Access Control and Helm</h3><p>Kubernetes has a powerful and elegant system for configuration of role and privilege. Users, and groups of users, can be granted various permissions, either cluster wide via ClusterRoleBindings, or within specific namespaces via RoleBinding. We will not attempt to describe the details of RBAC here, but one particular aspect is worth additional attention.</p><p>Our goal in configuring RBAC is to give the developer the freedom to work directly with the k8s API via any tools they wish, whilst simultaneously trying to provide a degree of protection for services required by our infrastructure team. We would like teams to be able to share clusters, but would also like to be able to segregate their jobs when required. The strategy we have settled on is to give developers full access to namespaces, based on their Google Cloud group membership. All teams share access to the default namespace. Teams can have their own namespace, or namespaces for specific applications. The infrastructure team have a namespace for running more privileged applications (for instance, requiring unavoidable, high value secrets). No teams deploy anything to, or interact with, the kube-system namespace.</p><p>There are several choices for how to go about provisioning your services into k8s clusters. Most tutorials focus on using kubectldirectly, there are also several templating solutions. For better or worse, we have settled on <a href="https://github.com/kubernetes/helm">Helm</a>. Helm’s concept of a release, with history and rollbacks, provides us a nice model for managing all aspects of a deploy. Rebuilding our existing deployment tool (that targets Docker and Marathon), to support Helm was relatively straightforward.</p><p>One downside of Helm is Tiller. Tiller is a small service deployed in your cluster which acts as the state store for Helm, keeping the required and previous configuration state in k8s configmaps. Tiller must be installed in the cluster, and must have permission to create resources. It is no longer our users doing the deploying, Tiller does this for them.</p><p>By default Tiller is installed to the kube-system namespace. A regular install would likely give Tiller, and by extension the developer using Helm to deploy to it, full access to all k8s namespaces. In multi-tenant clusters that is not acceptable. Fortunately this can be avoided.</p><p>Let us say we have a team called team-a. We will create a namespace for them, and grant them full privileges to a namespace, also called team-a.</p><pre>$ kubectl create namespace team-a<br>$ kubectl create rolebinding team-a-admin --namespace team-a \<br>  --clusterrole=cluster-admin --group=team-a</pre><p>This creates the namespace and assigns the cluster-admin ClusterRole, as a RoleBinding in the team-a namespace, to members of team-a. It is important to note that this is a RoleBinding tied to the namespace, not a ClusterRoleBinding, which would give cluster-admin rights to the entire cluster. It seems odd but you can bind a ClusterRole with a RoleBinding, with the subsequent access being allowed only to a specific namespace.</p><p>Now, if we deploy Tiller to this namespace, it will get the default service account. This account does not have sufficient privileges to manage resources in the namespace. Instead we create a service account for Tiller, and create it a RoleBinding that binds it to the cluster-admin ClusterRole in our team-a namespace.</p><pre>$ kubectl create --namespace team-a serviceaccount tiller<br>$ kubectl create --namespace team-a rolebinding team-a-tiller \<br>  --clusterrole=cluster-admin --serviceaccount=team-a:tiller</pre><p>We can now deploy Tiller:</p><pre>$ helm init --upgrade --tiller-namespace team-a \<br>  --service-account tiller</pre><p>And our developers can finally use it:</p><pre>$ helm --tiller-namespace team-a install alpha/hackernewsthing</pre><p>By restricting our developers to particular namespaces we gain an additional layer of security, and can also hide some of the guts of our internal cluster management tooling from them. It gives us more options for controlling resource quotas on a per-namespace basis, and potentially segregating work on the underlying VMs via namespaces too (this would require admission control, but should be possible).</p><h3>When is AWS is more GCP than GKE?</h3><p>One curious aspect of the configuration described above is worth further discussion. Our own token issuing service fully exposes the group membership of the user by embedding them in the JWT token. Google’s equivalent tokens, the ones we use when talking to GKE via IAM, do not. There are sound technical reasons for this. At Google’s scale, resolving group memberships is an expensive operation. At our scale it is not. The practical upshot of this though is that in GKE we cannot use RBAC rules to limit the namespaces a given user can manage.</p><p>In GKE we must grant the developer broad rights to, at the very least, see the cluster. It is technically possible, via <a href="https://stackoverflow.com/questions/45945074/iam-and-rbac-conflicts-on-google-cloud-container-engine-gke">custom IAM Policies</a>, to restrict this to a very minimal set of rights, however, our RBAC policies can only ever match specific users, or everyone that is authenticated, not groups. The practical upshot is that we must give the developer full access to the cluster, allowing them full visibility, and management, of all namespaces. As well as the obvious security implications, this also exposes the developer to having to see a large number of API objects which they have no interest in.</p><p>We can create smaller clusters, assigning IAM rights to entire clusters, but to smaller teams, however the extra clusters create an operational burden, and ultimately are less cost effective in terms of resource usage.</p><p>For the moment we are accepting the coarser IAM permissions. Google are working on this issue. It will be interesting to see how well integrated into RBAC their final approach will be. In the longer term, if a suitable solution is not found, we still have the option of building kops clusters on GCP. The gap in features between a GKE cluster and a kops GCE cluster is less than one might imagine. As you will see in Ingress and Observability sections later on, we leverage less GKE features than one might reasonably expect, and the additional access to direct Kubernetes API Server features may outweigh the benefits of GKE in the long run.</p><h3>Summary</h3><p>With the configuration described above we have a solid basis for multi-tenant clusters. Authentication is built on top of a preexisting company standard, and is relatively consistent between our two cloud providers. Google G Suite remains our single source of truth for group membership, and thus authentication and authorisation. kubectl’s cmd-path feature has allowed us to ensure that the developer’s experience of using the clusters is in line with what they will find in any Kubernetes tutorial on-line.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d2c908c2810" width="1" height="1" alt=""><hr><p><a href="https://medium.com/qubit-engineering/kubernetes-up-integrated-authentication-5d2c908c2810">Kubernetes: Up &amp; Integrated — Authentication</a> was originally published in <a href="https://medium.com/qubit-engineering">Qubit Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Plumbing Big Data Pipelines]]></title>
            <link>https://medium.com/qubit-engineering/plumbing-big-data-pipelines-e9a0faa6f479?source=rss----a1e5a35d34d7---4</link>
            <guid isPermaLink="false">https://medium.com/p/e9a0faa6f479</guid>
            <category><![CDATA[akka]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[qubit]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Charith Ellawala]]></dc:creator>
            <pubDate>Wed, 06 Sep 2017 07:20:04 GMT</pubDate>
            <atom:updated>2017-09-07T10:22:48.037Z</atom:updated>
            <content:encoded><![CDATA[<p>Qubit’s Visitor Cloud receives over a billion events a day from thousands of customer websites and mobile applications all over the world. Our service level objective is to have these events validated, enriched and available for consumption by our stable of personalisation and business intelligence products within 10 seconds of reaching the perimeter of Qubit.</p><p>If we compare Qubit Visitor Cloud to the human circulatory system, the heart would be the fleet of ingestion servers that receive all the raw event data piped over the internet from various different sources. These data points get written to a Google Cloud Pub/Sub topic — which is analogous to the aorta, the main artery connected to the heart. At peak, the ingestion servers write over 20,000 batches a second to this Cloud Pub/Sub topic. This forms the entrypoint to Qubit’s stream processing system that leverages Cloud Dataflows to validate, enrich and persist the data to our data warehouse. We break the batches into individual events after validation — which results in over a 100,000 messages a second flowing downstream at peak.</p><p>After successfully building and deploying the high-speed stream processing system, one of the most common questions posed to us by other engineering teams was how they could easily tap into the data stream and build systems that react to interesting events happening in our customers’ online properties. One quick solution would have been to use the data warehouse and periodically poll for data. However, we felt that aside from being inelegant and inefficient, this approach has several major drawbacks.</p><ul><li><strong>Periodic polling introduces artificial delays</strong><br>If the polling interval is two minutes, for example, then reactions to some events could take at least two minutes.</li><li><strong>State management becomes tedious and complex</strong><br>For polling to work effectively, the system needs to checkpoint its state to avoid duplicate processing. This becomes even more complicated when we consider that data collection over the internet can introduce arbitrary delays beyond our control and any serious data processing system needs to consider how to detect and handle late arrivals. Naive polling solutions run a very high risk of missing some data and/or processing some data points more than once.</li><li><strong>Resource contention and duplication of effort</strong><br>A handful of polling applications might not have any noticeable impact on the data warehouse. However, as the number of applications grow, they will compete for resources — degrading the experience for both interactive and non-interactive users. Furthermore, typical data access patterns in a data warehouse involves a few “hot” fact tables. The chances are high that most of the applications will be duplicating the logic and work required to query those few core tables.</li><li><strong>Cost</strong><br>Qubit’s main data warehouse is built on BigQuery. Queries are charged based on the number of gigabytes accessed. When the data warehouse consists of <a href="https://www.youtube.com/watch?v=9nhoWpPKA1M">petabytes of data</a>, even simple queries can start incurring non-trivial costs.</li></ul><p>The other option would have been to provide every interested team with a subscription to the main firehose. However, most teams are interested in only a handful of events and asking them to build systems that can deal with hundreds of thousands of messages in real time, only to discard most of it seemed wasteful and would have introduced a high barrier for entry. Furthermore, doing so would have increased our Cloud Pub/Sub operating costs as well.</p><p>After careful consideration, we decided that the best course of action would be to provide some sort of a stream router. Users should be able to specify the messages they were interested in, and the system should route all messages matching the criteria to a Cloud Pub/Sub topic of choice. This system would be connected to the main firehose on one end and many different Cloud Pub/Sub topics on the other end, similar to a “manifold” in plumbing (and automotive) parlance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*x790Hvvg-oEfv1wd.jpg" /><figcaption><a href="https://flickr.com/photos/ricardojesusflores/35760067926">Hytech S2000 Exhaust Manifold</a> flickr photo by <a href="https://flickr.com/people/ricardojesusflores">Ricky Flores</a> shared under a <a href="https://creativecommons.org/licenses/by/2.0/">Creative Commons (BY) license</a>.</figcaption></figure><p>Our first inclination was to build the Manifold using Cloud Dataflow itself. It was a system we were already intimately familiar with and had successfully deployed to production. However, the requirement to add/remove/update routes while the system was running and dynamically configure output sinks proved to be a major problem. While we could potentially overcome the first problem by polling a data source for routing updates, the issue of dynamically adding output sinks to a Cloud Dataflow was a harder problem to solve. One option we considered was to use the Cloud Pub/Sub API from within a DoFn to write to many topics as we wanted. However, this felt like a brittle solution that would be harder to reason about and debug. It also didn’t quite fit into the Cloud Dataflow model of processing and violated the principle of least astonishment.</p><p>We then turned to Akka Streams, a framework that we had already used in a couple of projects with great success. Our first foray was when the Akka Streams project was in its infancy to build an internal metrics reporting tool for a large HBase cluster. The APIs and the specifications changed significantly leading up to the 1.0 release and we again used it successfully to glue our old data processing pipeline to the new one while we were in the process of migrating to the Google Cloud. We were extremely impressed by how an Akka Streams application running on a single machine was able to effortlessly copy our Kafka firehose to Cloud Pub/Sub in real time. Since it had already proven itself as a reliable workhorse, we had no doubts about its suitability for the Manifold system.</p><p>The implementation was not without challenges though. The first hurdle was the lack of Cloud Pub/Sub Sources and Sinks for Akka. At the time we started working on the project, Google had just published the gRPC API definitions for Cloud Pub/Sub. As all of our backend systems were already using gRPC, it was a natural choice to implement the Akka Stream sinks and sources in gRPC as well. We have used this implementation in production for more than a year to process hundreds of billion events that amount to hundreds of terabytes of data by volume. The Sinks and Sources are now open-source and can be obtained from the Git repository at <a href="https://github.com/QubitProducts/akka-cloudpubsub">https://github.com/QubitProducts/akka-cloudpubsub</a>. (We will soon release an update that takes advantage of the recently introduced streaming pull feature of Cloud Pub/Sub.)</p><p>The second hurdle was the one we faced with the Cloud Dataflow system we were considering earlier as well. As Akka stream graphs are materialised in advance and executed, how could we make the system write to Cloud Pub/Sub topics that are unknown at materialisation time. It seemed like an insurmountable problem where the only solution seemed to be re-materialising and launching the stream graph on every change until we stumbled onto an undocumented feature of Akka Streams called “<a href="http://doc.akka.io/api/akka/current/akka/stream/stage/GraphStageLogic$StageActor.html">stage actors</a>”. Stage actors are a mechanism by which code can safely interact with the actors running the stream stages of the materialised graph. By interacting with the stage actor, we can dynamically alter the stage processing logic at runtime — allowing updates to routing specifications to take effect immediately without re-materialising the stream graph.</p><p>After solving the fundamental issue of dynamic routing, our next concern was scaling the system to deal with ever increasing traffic volumes in the main firehose. We addressed this by making Manifold a clustered application using Akka Cluster. The advantage of this approach is that new nodes can be added or removed from the system with almost no effort. Newly launched nodes automatically join the cluster, obtain the current routing specifications from the coordinator and start running the stream graph. Updates are communicated by the coordinator to all nodes through the Distributed Publish Subscribe mechanism provided by Akka Cluster. Thanks to Akka’s persistent actor mechanism, the coordinator does not become a single point of failure either. If the current coordinator becomes unresponsive, another coordinator will automatically take over with no data loss as the state is checkpointed to persistent storage on every update.</p><p>Users are provided with a CLI application that allows them to submit routing specifications written using a YAML-based DSL to the gRPC controller that runs alongside the cluster. The controller validates the incoming requests, checks permissions on relevant Cloud Pub/Sub topics (creating them if necessary), converts the specification to a Protobuf-based binary representation and submits the state change to the cluster coordinator. The cluster coordinator then publishes the change to the cluster members.</p><p>Manifold is deployed on a managed Kubernetes cluster on Google Container Engine which allows us to easily scale the system as necessary. It was surprisingly easy to plug in Kubernetes service discovery primitives to Akka cluster so that pods can join and leave the cluster effortlessly. The Kubernetes cluster makes use of the auto-scaling functionality provided by Google Container Engine to automatically expand and shrink the cluster according to demand. This has become particularly useful in handling sudden traffic spikes resulting from flash sales and social media campaigns run by our customers to promote their website traffic.</p><p>Manifold has been in production use at Qubit for over a year and has enabled us to quickly prototype and build new products that take full advantage of the near real-time availability of data from our data processing pipeline. (<a href="http://www.qubit.com/solutions/customer-polling-and-feedback">Visitor Pulse</a> and <a href="http://www.qubit.com/solutions/adaptive-targeting#adaptivetargeting">Adaptive Targeting</a> are two examples of products that rely on Manifold to tap into the filtered event stream.)</p><p>If you relish these sorts of engineering challenges, we have plenty more in store. Check out <a href="https://eng.qubit.com/">Qubit careers</a> for more information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9a0faa6f479" width="1" height="1" alt=""><hr><p><a href="https://medium.com/qubit-engineering/plumbing-big-data-pipelines-e9a0faa6f479">Plumbing Big Data Pipelines</a> was originally published in <a href="https://medium.com/qubit-engineering">Qubit Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to monitor a queue based application]]></title>
            <link>https://medium.com/qubit-engineering/how-to-monitor-a-queue-based-application-2fa534d074d4?source=rss----a1e5a35d34d7---4</link>
            <guid isPermaLink="false">https://medium.com/p/2fa534d074d4</guid>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Laurie]]></dc:creator>
            <pubDate>Mon, 15 May 2017 10:11:54 GMT</pubDate>
            <atom:updated>2017-05-15T10:11:54.381Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stash Deferred</h3><p>At Qubit, we have a service named ‘Stash Deferred’. It reads from a database, <a href="https://cloud.google.com/bigtable/">GCP’s Cloud Bigtable</a>, and writes to <a href="https://aws.amazon.com/kinesis/streams/">AWS’s Kinesis</a>. Recently it underwent a bit of a renovation by the team that I am on, and a colleague commented that the end result had quite good monitoring, potentially worth of being a case study. So here’s that.</p><p>Stash Deferred is a system for deferring message writes. A user sends, via a HTTP call, a message, and an expiry timestamp. When the expiry time is reached, the message is put onto the Kinesis queue. There is no guarantee of ordering given.</p><p>Bigtable is a key value store that supports ‘get’, ‘set’, ‘delete’ and ‘scan’. Scan allows you to request values between two keys, in lexicographical (alphabetical) order. This is the operation that Stash Deferred uses to fetch messages that should be sent. Every interval we send a request for all of the values with keys between ‘deferred:’ and ‘deferred:’. These are the messages have ‘expired’, and should be put onto the Kinesis queue.</p><p>So, fairly simple. We read rows from Bigtable, publish their contents to Kinesis, then delete them from Bigtable. This look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fH0Jj8rCLpRCc_6f623VJg.png" /></figure><p>The internal arrows here are unbuffered Go channels. We use them as we perform the operations at different rates; scans happen in large batches, publishes are unbatched, and deletes use small batches.</p><p>All of the monitoring here is going to be done using <a href="https://prometheus.io/">Prometheus</a>, with some small bits of <a href="https://grafana.com/">Grafana</a>. I guess you could replicate most of this with other monitoring systems, though I’m not sure why you’d want to. Give Prometheus a go. It’s pretty good.</p><h3>Basic Monitoring</h3><p>There are three main operations here that we want to monitor; scan, publish, and delete. For each of these operations (and basically any operation in any application) there are two properties we can easily instrument: duration and count. I’ll use the Kinesis publisher as my example for this. We define two metrics:</p><pre>var (<br> kinesisWriteCount = prometheus.NewCounterVec(<br>  prometheus.CounterOpts{<br>   Name: &quot;stashdef_kinesis_message_write_total&quot;,<br>   Help: &quot;count of kinesis messages written, tagged by result&quot;,<br>  },<br>  []string{&quot;result&quot;},<br> )<br> kinesisWriteDuration = prometheus.NewHistogram(<br>  prometheus.HistogramOpts{<br>   Name:    &quot;stashdef_kinesis_message_write_duration_seconds&quot;,<br>   Help:    &quot;duration of kinesis write operations&quot;,<br>   Buckets: prometheus.ExponentialBuckets(0.1, math.Sqrt(10), 6),<br>  },<br> )<br>)</pre><p>If you’ve never seen Prometheus metrics before, then I’ll give you a brief explanation of what I’m declaring here.</p><p>The first metric is the variable kinesisWriteCount, which is registered as stashdef_kinesis_message_write_total on the Prometheus server. This might seem like a crazy long name, but there is a certain logic to it. Prometheus metrics follow the naming convention of &lt;namespace&gt;_&lt;metric name&gt;_&lt;units&gt;. In this case, our namespace is the abbreviated name of our program, stashdef. The name of the metric is always a little contentious, but kinesis_message_write is an understandable description of the operation we&#39;re monitoring. The unit is even less clear, using total. There is debate whether total or count is clearer to use when you&#39;re counting something, but I use total, as count is often used by the default Prometheus libraries, and my use is not always compatible with their use.</p><p>The other thing to note about this metric is that we have a label on it. Prometheus allows you to add labels to your metrics, adding additional dimensions. In Qubit, we have a convention of having a label called result, which has two values: success and failure.</p><p>The second metric is the variable kinesisWriteDuration, registered as stashdef_kinesis_message_write_duration_seconds. Much the same as the above, the key differences are that this is a histogram. A histogram is made up of a number of counters, each representing a different bucket. Here I set up a set of exponentially distributed buckets, with 0.1 being my starting bucket, root 10 being my exponent, and 6 being the number of buckets. This results in rough buckets of request counts where the durations were between [0,0.1), [0.1,0.316..), [0.316..,1), etc etc. The use of math.Sqrt(10) as the exponent gives us 2 buckets per order of magnitude, which is useful to cover a large range of possible durations when you don’t always know what the ‘normal’ range for the operation is.t</p><p>The other change is in the name of the metric, where we exchange total for duration_seconds. Adding the unit to the metric name makes life easier for everyone involved, and seconds is preferred for durations, given its SI status. All Prometheus metrics are 64 bit floating point numbers, so the number of cases where using seconds as a unit could cause issues is negligible.</p><p>With our metric set up, we can now instrument our publishing code.</p><pre>func (k *KinesisWriter) Write(ctx context.Context, messageChan &lt;-chan Message, delchan chan&lt;- string) error {<br> for {<br>  var msg Message<br>  select {<br>  case &lt;-ctx.Done():<br>   return ctx.Err()<br>  case msg = &lt;-messageChan:<br>  }</pre><pre>started := time.Now()<br>  err := k.publish(msg)<br>  if err != nil {<br>   log.Warningf(&quot;could not publish message: %v&quot;, err)<br>   kinesisWriteCount.WithLabelValues(&quot;failure&quot;).Inc()<br>  } else {<br>   kinesisWriteCount.WithLabelValues(&quot;success&quot;).Inc()<br>  }<br>  kinesisWriteDuration.Observe(float64(time.Since(started)) / float64(time.Second))</pre><pre>select {<br>  case &lt;-ctx.Done():<br>   return ctx.Err()<br>  case delchan &lt;- msg.AckId:<br>  }<br> }<br>}</pre><p>Gripping stuff. I’ve omitted some code that handles retries and suchlike. With this, we get some incredibly useful metrics. Let’s play with them.</p><p>The first thing I’d like to see is the throughput of my system. This is the rate of increase of the write count metric:</p><pre>rate(stashdef_kinesis_message_write_total[1m])</pre><p>As our metric is not a continuous function, we can’t simply differentiate it, so we need to specify over what period we want our rate to be calculated. This is the period in the square brackets. 1m is a convention within Qubit, along with 30m for when you want a calmer, PM friendly, view. In general, the smaller the window, the less data required, the faster the result.\</p><p>A general note about rates: it is statistically meaningless to compare two metrics that have been calculated using rates across different intervals. This is why it is so important to develop strong conventions around rate intervals. Imagine a (contrived) situation where your ops team has calculated network traffic rates at the 5m interval and you have calculated row processing rate at the 30m interval. Any comparison between the two metrics now becomes a statistical minefield that would make Brian Brazil very unhappy if he learnt about it.</p><p>When we graph this in the Prometheus UI, we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yXYjEnCNCgkAg4w5W4HW5Q.png" /></figure><p>What we see here is that Prometheus has calculated the rate for each set of labels we have sent. In the graph’s legend, we can see the set of labels that Prometheus has associated with our metrics. Many of them are generated by Prometheus based on the metadata attached to our application’s deployment, but on the far right we can see the result metric. If we had more that one instance of the application running, we would end up with more than 2 lines. To merge those lines together, we need to specify an aggregation method. In this case, as we are interested in the throughput of the system, we probably want to sum all the lines together, to get the number of messages we are handling per second:</p><pre>sum(rate(stashdef_kinesis_message_write_total[1m]))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c4J4LJwvYUzOQqRrv_b5mQ.png" /></figure><p>Realistically, the information we want on our Grafana dashboard is probably the overall success and error rates. We can do this by summing over a specific label. This is similar to the GROUP BY statement in SQL:</p><pre>sum(rate(stashdef_kinesis_message_write_total[1m])) by (result)</pre><p>Putting that on our dashboard, we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*omuNuhQcHwruOVXHF4IJ7Q.png" /></figure><p>Beautiful. No errors! Let’s take a look at our duration metrics next.</p><p>With duration, we have no choice but to show a statistic, as a time series of a histogram is not particularly possible when we only have two dimensions. An easy to calculate statistic is the mean time the publish operation takes.</p><pre>rate(stashdef_kinesis_message_write_duration_seconds_sum[1m]) /<br>  rate(stashdef_kinesis_message_write_duration_seconds_count[1m])</pre><p>However the mean is a widely discredited statistic in monitoring circles. Much preferred is the quantile. Prometheus allows us to calculate quantiles from histograms using the <a href="https://prometheus.io/docs/querying/functions/#histogram_quantile">histogram_quantile function</a>.</p><pre>histogram_quantile(0.99,<br>  rate(stashdef_kinesis_message_write_duration_seconds_bucket[1m]))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Luhatd-ATSL9vpwmu4PvSw.png" /></figure><p>Here we can see that our 99%th percentile publish duration is usually 300ms, jumping up to 700ms occasionally. One great thing about Prometheus is that there is rarely any confusion over the units, as functions do not as a rule change units between input and output.</p><p>Let’s put this quantile, along with 50% and 90%, on our Grafana and admire the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*XnpeXQtgDBQ54u0F-_4TGA.png" /></figure><p>And now repeat for the other two operations. We now have basic instrumentation that we could apply to pretty much any operation in any program, and get some form of useful result.</p><h3>Slightly interesting monitoring</h3><p>Is there anything more we need to measure about our program? There are a few things that this program does that verge on interesting, and we should probably get some visibility on.</p><p>When we read from Bigtable, there is a chance that the row we read is one that we have read previously, and is currently in the process of being written to Kinesis or deleted from Bigtable. To combat this, we maintain a list of active records, and do not send rows to be published if they are in the list of actives. This gives a rate of duplicates, which we might like to measure.</p><pre>var (<br> bigtableScanDuplicateCount = prometheus.NewCounter(<br>  prometheus.CounterOpts{<br>   Name: &quot;stashdef_duplicates_filtered_total&quot;,<br>   Help: &quot;Count of duplicate messages filtered on scan&quot;,<br>  },<br> )<br>)</pre><pre>func (b *BigtableScanner) Scan(ctx context.Context, messageChan chan&lt;- Message) error {<br>...<br> if b.IsActive(msg) {<br>  bigtableScanDuplicateCount.Inc()<br> } else {<br>  select {<br>  case &lt;-ctx.Done():<br>   return ctx.Err()<br>  case messageChan &lt;- msg:<br>  }<br> }<br>...<br>}</pre><p>This metric isn’t particularly interesting, but duplication is one of the states that a row finish in, so having visibility of it is useful. I doubt I’d ever alert on it, but I might graph it during an incident to see if anything funky was going on.</p><h3>Building a diagram</h3><p>With that metric, we now have visibility on every exit point of a row from our application. At Qubit we have a third party plugin installed in our Grafana, <a href="https://grafana.qutics.com/plugins/jdbranham-diagram-panel/edit">jdbranham’s diagram plugin</a>. It lets you create diagrams using <a href="https://knsv.github.io/mermaid/">Mermaid</a> syntax, and then annotate them and style them based on the value of metrics. This allows you to produce something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cLjbTcikz67FU8SQsFweZQ.png" /></figure><p>This gives us an overview of how the system works, which is incredibly useful all on its own, and a quick look at the rates going through each component.</p><p>The value here isn’t in the quality of the data, as obviously a chart showing us these values over time would give us a much better dataset with which to judge things on. The value is the ability for anyone in the company to come to the Grafana page and see at a glance the components that make up the system.</p><p>Dashboards aren’t just about showing data. They also need to be interpretable by people, preferable including the people who didn’t create the dashboard. This is why giving plots titles, units, and even descriptions makes the difference between some metrics on a page and an actual dashboard. The diagram is just another tool in that direction.</p><p>The diagram plugin takes two main set of inputs. The first is the Mermaid specification for the diagram, and the second is the mapping from node on the diagram to metric.</p><p>The Mermaid specification for the above graph is provided below. It’s pretty incomprehensible, and the only way you’ll get any value out of this section is by installing the diagram plugin and trying out it out.</p><pre>graph LR<br>subgraph stash<br>W[User] ==&gt; S<br>end</pre><pre>S(Stash) ==&gt; A[BigTable]</pre><pre>subgraph deferred-backend<br>A ==&gt; B(BT Scaner)<br>B --&gt; B1&gt;Duplicate]<br>B --&gt; B2&gt;Error]<br>B ==&gt; C(Kinesis Publisher)<br>C --&gt; C1&gt;Error]<br>C ==&gt; D(BT Deleter)<br>D ==&gt; A<br>D --&gt; D1&gt;Error]<br>end<br>C ==&gt; E[Kinesis]</pre><p>Each of the names of the nodes (A, B, etc) needs a metric to go along with it. I really recommend using the same units for every metric in the diagram. I&#39;ve gone with sum(rate(&lt;metric&gt;[1m])), and I explain that in the title. This bit is super boring, as you&#39;re just matching up labels to metrics.</p><p>General notes on the diagram plugin:</p><ol><li>It’ll look ugly. I know. I’m sorry.</li><li>I wish I could use dot syntax, but the fact that Mermaid is so limiting but the plugin is still so useful speaks to the power of diagrams.</li><li>Use shapes to classify components. I use rectangles for datastores, rounded rectangles for processes, and the weird asymmetric shape for resulting states.</li><li>Avoid squares, circles and rhombuses. Their volume increases at the square of the length of any text inside them. This means that a square Duplicate would be much bigger than a square Error, suggesting to the user there are more duplicates happening than errors.</li></ol><h3>Top users</h3><p>Nothing we’ve done so far introspects the data coming through our system. One common question during an incident relating to volume is ‘did someone start sending something new’? We can add a metric to capture this.</p><pre>var (<br> kinesisDecodeCount = prometheus.NewCounterVec(<br>  prometheus.CounterOpts{<br>   Name: &quot;stashdef_kinesis_message_decode_total&quot;,<br>   Help: &quot;count of kinesis messages written, tagged by stream name&quot;,<br>  },<br>  []string{&quot;stream&quot;},<br> )<br>)</pre><p>This metric has the tag stream, which contains the name of the Kinesis stream we are publishing the messages to.</p><p>Now, there are issues with this, the primary being that the values of stream are unbounded. Prometheus scales primarily with the number of metrics, and each new value of stream creates a new metrics. However, in our situation, we are only creating a single metric per stream value, and the value of being able to see different stream names is greater than the risks involved. When we graph this, we probably only care about the top few streams. For this, we can use Prometheus&#39;s <a href="https://prometheus.io/docs/querying/operators/#aggregation-operators">topk aggregation</a>.</p><pre>topk(4, sum(rate(stashdef_kinesis_message_decode_total[1m]) by (stream))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*M_jRh6oRLPfv85oZKDPlEQ.png" /></figure><p>I’m never 100% sure if this is worth it. There have been dashboards where I have displayed this metric, then removed it, and the re-added it. It’s probably worth having, but looking at it for too long will turn it into a vanity metric.</p><h3>Backpressure</h3><p>When the system reaches saturation, the limiting factor is the Bigtable scanner. However, it’s perfectly possible that the Kinesis publisher could become very slow, or that the Bigtable deleter could slow down. As the channels between the components are unbuffered, a slowdown upstream should cause the send on the channel to slow down, and by measuring this, we can get a sense of it there is a non scanner slowdown. Implementing this is easy enough.</p><pre>var (<br> bigtableScanBackpressure = prometheus.NewHistogram(prometheus.HistogramOpts{<br>  Name:    &quot;stashdef_bigtable_row_scan_backpressure_seconds&quot;,<br>  Help:    &quot;Backpressure on the channel out of the row scan&quot;,<br>  Buckets: prometheus.ExponentialBuckets(0.001, 3, 6),<br> })<br>)</pre><pre>func (b *BigtableScanner) Scan(ctx context.Context, messageChan chan&lt;- Message) error {<br>...<br> sendStarted := time.Now()<br> select {<br> case &lt;-ctx.Done():<br>  return ctx.Err()<br> case messageChan &lt;- msg:<br> }<br> bigtableScanBackpressure.Observe(float64(time.Since(sendStarted)) / float64(time.Second))<br>...<br>}</pre><p>This metric is almost always incredibly low, as a channel send is very fast when there is a listener on the other end. However, as soon as there is a delay upstream, this metric becomes very important.</p><p>Plotting this in Grafana, I take the same approach as our other duration based metrics, using quantiles at 50%, 90%, and 99%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*DzHXB8yyAbW5l8qYvp1XmA.png" /></figure><p>The use of a log scale here makes it easier to handle the massive difference between an unhindered send, which is under 1ms, and a hindered send, which can be in the 100s of milliseconds.</p><h3>Pageable metrics</h3><p>I wouldn’t page on any of the metrics we’ve collected so far. The key property for an alert being pagable is user impact, and everything we’ve talked is very much a cause, not a symptom. To work out what we want to page on, we need to think about what happens when our system fails, and what do our users experience. In this case, there are two main symptoms; message lag and message drops.</p><p>To measure these, we have a completely separate application. This application (I call it lag-monitor) periodically sends messages with very short expiry, and then listens to the destination queue to see how long it takes before a message comes through. This exposes two main metrics</p><pre>const (<br> stashDeferredLag = prometheus.NewGauge(prometheus.GaugeOpts{<br>  Name: &quot;stashdef_lag_seconds&quot;,<br>  Help: &quot;The last Stash deferred lag&quot;,<br> })<br> stashDeferredLastReceived = prometheus.NewGauge(prometheus.GaugeOpts{<br>  Name: &quot;stashdef_last_received_timestamp_seconds&quot;,<br>  Help: &quot;The timestamp when we last received a message from Stash deferred&quot;,<br> })<br>)</pre><p>I’m going to omit the code that writes to these metrics, as it’s fairly involved<br>in talking to the frontend of the service, though it looks a little like.</p><pre>func sender(...) {<br> for time.Tick(interval) {<br>  sendMessage(time.Now())<br> }<br>}<br>func receiver(...) {<br> for msg := range receiveMessages() {<br>  lag := time.Since(msg.SentAt)<br>  stashDeferredLag.Set(float64(lag) / float64(time.Second))<br>  stashDeferredLastReceived.Set(time.Now().UnixNano() / 1e9)<br> }<br>}</pre><p>Notably, this monitors more than just the Stash Deferred service, it also<br>monitors the service that inserts messages into the BigTable database. You could question whether this really constitutes monitoring for this service, but if the frontend goes down then my service’s users are affected, and I want to know when that happens.</p><p>The current lag can then be calculated as the time since we got a message, plus the lag on that message. This looks like</p><pre>(time() - max(stashdef_last_received_timestamp_seconds)) + max(stashdef_lag_seconds)</pre><p>We don’t just track the stashdef_lag_seconds as if the lag monitor were to fail, that metric would stop updating. The safest measure of lag is the lag measured by the lag monitor plus the time since we last measured that lag, as if the lag monitor fails, the result of time() will continue increasing regardless.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aS4g8qzvyO4d38VSSrSo-A.png" /></figure><p>The spiky nature of this graph comes from our use of Prometheus’s <a href="https://prometheus.io/docs/querying/functions/#time()">time function</a>, which steadily increases, while the last received metric resets every time we get a message.</p><p>This is the metric I want to alert on. Let’s write a Prometheus alert on this</p><pre>job:stashdef_lag:seconds =<br>  (time() - max(stashdef_last_received_timestamp_seconds)) + max(stashdef_lag_seconds)</pre><pre>ALERT StashDeferredLagHigh<br>  IF job:stashdef_lag:seconds &gt; 5 * 60<br>  FOR 2m<br>  LABELS {<br>    slack_channel=&quot;stash-deferred&quot;<br>  }<br>  ANNOTATIONS {<br>    description=&quot;Stash deferred messages are arriving {{ $value }} seconds after they were scheduled (threshold 5m)&quot;<br>  }</pre><p>Here we set up a <a href="https://prometheus.io/docs/querying/rules/">recording rule</a> to continuously calculate and store our lag, along with an alert on that lag calculation. The alert syntax is a wee bit odd, but should read: the alert StashDeferredLagHigh will fire if the metric job:stashdef_lag:seconds is greater than 300 for 2 minutes. When it fires, it should send to the slack channel stash-deferred, with the following description [description omitted].</p><p>The durations specified in the alert above are a bit arbitrary, and will be subject to tweaks over time. With the current setup, we can say that should the process stop processing messages altogether, it will take 4 minutes before the metric is above 300 seconds (i.e. 5 minutes of lag), and then another 2 minutes before the alert will fire. This is perfectly acceptable for this system. Your system may have very different users who rely on a different guarantees.</p><p>The Slack integration is set up in our <a href="https://github.com/prometheus/alertmanager">alertmanager</a> config. I’d really recommend integrating with whatever chat system your organisation uses. Recording rules are also a great idea, and in general if you want a dashboard to load quickly, I’d recommend implementing the queries you are plotting as recording rules.</p><h3>Putting it together</h3><p>Our final dashboard looks like…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S6f4WcVdQJ3QFh4u2DkAQw.png" /></figure><p>The additions made here are:</p><ol><li>The Bigtable deletion rate graph. Failed Bigtable deletions can result in duplicate messages, so we prioritise this metric.</li><li>Component memory usage. This is a metric fetched from the Kubernetes cluster, and is mostly there so I can say ‘look how efficient it is!’</li></ol><p>In the future, as I gain more experience operating this service, I plan to demote some of the duration metrics to below the fold on this dashboard, as they seem to be subject to seemingly alarming changes under completely normal operation. I also hope to spend some time addressing dropped messages in a more holistic manner in the lag monitor component.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fa534d074d4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/qubit-engineering/how-to-monitor-a-queue-based-application-2fa534d074d4">How to monitor a queue based application</a> was originally published in <a href="https://medium.com/qubit-engineering">Qubit Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Seasonality in Prometheus alerting.]]></title>
            <link>https://medium.com/qubit-engineering/using-seasonality-in-prometheus-alerting-d90e68337a4c?source=rss----a1e5a35d34d7---4</link>
            <guid isPermaLink="false">https://medium.com/p/d90e68337a4c</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[prometheus]]></category>
            <dc:creator><![CDATA[Tristan Colgate-McFarlane]]></dc:creator>
            <pubDate>Wed, 25 Jan 2017 13:32:10 GMT</pubDate>
            <atom:updated>2017-01-25T19:41:35.208Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In this post, we will show a worked example of building a Prometheus alert for a typical user facing service.</blockquote><p>At Qubit we have recently completed a migration from our legacy<br>Shinken and Graphite based monitoring to a system built around<br><a href="https://prometheus.io/">Prometheus</a>, a modern time series database.</p><p>Prometheus has many features that are particularly well suited to our<br>current infrastructure. To pick a few at random,</p><ul><li>Works well in containerised environments.</li><li>Exporters are easy to write, and the existing client libraries are pleasant to use.</li><li>It was easy to get started, and has proved very adaptable to our more extreme use cases.</li></ul><p>One of its most appealing features is the rich query language. Once you are<br>over the initial learning curve, a world of possibilities awaits.</p><h4>Living with your errors.</h4><p>In high traffic environments, traditional check and threshold based alerting<br>begins to cause pain. Errors are a simple fact of life. For clients traversing<br>the internet, especially mobile clients, possibly travelling at high speed<br>through rolling green hills, timeouts are unavoidable. Anyone with a server directly connected to the Internet will know that not everyone is polite enough to send you perfectly formed HTTP request of the kind you intended to receive. As scale increases, failures within your infrastructure eventually become equally unavoidable.</p><p>If we have to live with a background of alerts, we need methods for determining when we should be worried, and when we should not. Fortunately statisticians have been hard at work for a great many year, creating the mathematical tools we need to achieve just that.</p><p>Imagine a simple service receiving traffic from the internet. If we have a<br>consistent rate of events, spotting anomalies should not be too difficult.<br>We could assume our traffic will remain within a fixed margin of this, and alert when levels go below or above the average level of traffic we have seen<br>recently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*nCD6Q28nNcNaGPvr." /><figcaption>Thresholds on steady traffic</figcaption></figure><p>Unfortunately, any service interacting with humans will be very unlikely to see traffic like this. Traffic isolated to one country will often show a “Camels<br>Hump” shape. Working out why you traffic is the shape it is can be fun, and quite enlightening.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*FIbnMQu5NK5PFct0." /><figcaption>Typical daily traffic pattern</figcaption></figure><p>On a global scale things do even out a little, but humans are not evenly distributed across the planet (distribution of land, and distribution of wealth over the surface of the earth have seen to that). People will talk of traffic following the sun, with peaks of traffic as each major region comes on line.</p><p>These factors make it hard for simple threshold based alerting to work. We cannot simply give a minimum and maximum level. No one set of thresholds will work reliably throughout the entire day.</p><h4>The Changing Seasons</h4><p>Rather than ask what the level of traffic is with respect to previous traffic today, we can instead ask if our expected traffic at this time is reasonable relative to some previous point in time that we expect to have approximately the same traffic levels. In statistics, this is termed “Seasonality”. In much the same way that we consider the weather in winter to to be similar from year to year, we can find the same similarity between traffic levels in our system over different time ranges.</p><p>The obvious choice is to compare our traffic today with our traffic 24 hours<br>ago. We can do this in Prometheus using the offset keyword. Let us assume we have a rule in place to create an aggregate of our average per-second rate of events over the previous hour.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/726291a50c239e6213fe7574d76b96fa/href">https://medium.com/media/726291a50c239e6213fe7574d76b96fa/href</a></iframe><p>We could create a rule to track the rate of events from yesterday, as follows.:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6866bca9dd6f4bca658ed88de7aaa77/href">https://medium.com/media/c6866bca9dd6f4bca658ed88de7aaa77/href</a></iframe><p>This can be very useful indeed, and give you a very quick “at a glance”<br>indication if things are more or less at the right levels. We could now monitor the difference between our current rate of events, and the previous days, and perhaps pick a simple threshold again.</p><p>However, things become more interesting if we take several offsets and collect them together. In Prometheus we can achieve this with the following rule.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d854d0a1d185320bf0c406566eb844d/href">https://medium.com/media/6d854d0a1d185320bf0c406566eb844d/href</a></iframe><p>Building up these historical views of our data can become quite mesmerising. But beyond produce pretty graphs, we can put this to more direct use. If each days samples are similar, we can do the following.</p><ul><li>Take the average of the rates of events for each of our previous days</li><li>Calculate the Standard Deviation between the previous days rates of events</li></ul><p>Standard deviation gives us a measure of how much we can expect other days to vary from the 3 days worth of samples we have. We can the calculate upper and lower bounds for what is reasonable to expect, and alert if we move beyond those levels.</p><p>Effectively we are dynamically creating out thresholds. In Prometheus we do this as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba6cf3e35377fcd8ecd38b928b0f5914/href">https://medium.com/media/ba6cf3e35377fcd8ecd38b928b0f5914/href</a></iframe><p>And finally we create an alert to inform us when we’ve moved beyond our<br>threshold. We will suggest that if our traffic is between ±3 standard<br>deviations from our previous levels things are looking fine. If we move<br>outside of those levels, we will raise an alert.</p><p><strong>Note</strong>: Whether or not this is reliable enough to be considered worthy of paging someone is really down to your particular levels and shape of traffic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b702a3606ebb150ee5cfa576b256fdc/href">https://medium.com/media/3b702a3606ebb150ee5cfa576b256fdc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*FljkSQ18Mc74zXlw." /><figcaption>Daily traffuc annotated with potential “safe levels”</figcaption></figure><h4>What is normal?</h4><p>If the underlying data samples conform to a <a href="https://en.wikipedia.org/wiki/Normal_distribution">normal distribution</a> ,3 standard deviations would suggest a 99.7% chance that we are experiencing a problem. In reality this is unlikely to be the case, but may be a reasonable estimation.</p><p>More traffic sample can help us tighten the our prediction. There is a further problem however. Just as our morning traffic and evening traffic are different, there are likely to be similar differences between individual days. If our weekend traffic differs in volume or shape from our weekday traffic, our calculation are off. Our alerts are likely to fire on Saturday, and fail to fire on a Monday morning. (This is caused by our sample points not actually being from a normal distribution.) We may see more correlation if we choose similar hours in each week, rather than simply each day.</p><p>One limitation you may run into with Prometheus, if trying to extend too far into the past, is with its retention periods. Prometheus is designed for alerting rather than data mining. The default retention period is 2 weeks. In very dynamic Environments it is often necessary to reduce this further.</p><p>This would seem to limit the historical series we can query, but we can perform a simple trick to “remember”, the old data for a specific set of queries.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e2fbe439a4e2e250e618db57ba53c80/href">https://medium.com/media/1e2fbe439a4e2e250e618db57ba53c80/href</a></iframe><p>This way, we can now produce an estimate based on 3 values of the last<br>3 weeks, even though our server may only actually hold 8 days worth of data. It is important to note that you should not mix these 1w samples in with your 1d samples above. The mean and stddev rules from above should be adjusted, perhaps as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8648268df3027e1f9730ac88447a0c58/href">https://medium.com/media/8648268df3027e1f9730ac88447a0c58/href</a></iframe><p>Alternatively we could store these with as one metric with a label. Adjusting<br>the final calculation and alert are left as an educational exercise for the<br>Reader.</p><h3>Conclusion</h3><p>Prometheus provides a powerful set of tools to help up build alerts based on a deeper understanding of our data than simple thresholds. This post has explored one such technique.</p><p>For those interested in more on this topic, I highly recommend this <a href="https://www.youtube.com/watch?v=gNmWzkGViAY">video</a> below (and the related Better Living Through Statistics talks), by Jamie Wilkinson, and his excellent contributions to <a href="http://shop.oreilly.com/product/0636920041528.do">O’Reilly’s Site Reliability Engineering</a> book.</p><p>Those interested in a more rigorous discussion of the maths can find many great books to choose from, but could do worse than <a href="https://www.amazon.co.uk/Statistics-Nutshell-Desktop-Reference-OReilly/dp/0596510497">Statistics in a Nutshell</a></p><p><em>Look out for future posts discussing how we’re leveraging Prometheus at Qubit.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d90e68337a4c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/qubit-engineering/using-seasonality-in-prometheus-alerting-d90e68337a4c">Using Seasonality in Prometheus alerting.</a> was originally published in <a href="https://medium.com/qubit-engineering">Qubit Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Celebrating the dead (projects)]]></title>
            <link>https://medium.com/qubit-engineering/celebrating-the-dead-projects-bf58ee0f5cc1?source=rss----a1e5a35d34d7---4</link>
            <guid isPermaLink="false">https://medium.com/p/bf58ee0f5cc1</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[startup-culture]]></category>
            <dc:creator><![CDATA[Emre Baran]]></dc:creator>
            <pubDate>Thu, 11 Feb 2016 15:01:01 GMT</pubDate>
            <atom:updated>2016-02-11T15:01:01.037Z</atom:updated>
            <content:encoded><![CDATA[<p>Engineers are perfectionists by nature. Celebrating success is not something they are good at because of the nagging feeling that things could be improved further. As a result we have not celebrated all the successes that we should have. Recently, we have discovered and started celebrating a new type of event at <a href="http://eng.qubit.com/">Qubit Engineering</a>: celebrating the dead products, features or code bases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-YRo0N3vijOVWHR1m-9x3w.png" /></figure><p>Historically, product and feature launches at Qubit have been very subdued affairs. This is partly due to what we felt were incomplete launches. We launch products early so we validate our ideas and learn about the market’s needs.</p><blockquote>As Reid Hoffman put it: “If you are not embarrassed by the first version of your product, you’ve launched too late.”</blockquote><p>When we launch early, in the back of our mind, we always know too that there are many more things to build and enhance before we can be really proud of a product. We are obsessed with making our products the best there is — not just in terms of features and great user experience but also in terms of the underlying engineering. As a result, there is always one more refactoring to be done or one more optimization to add. In moderation, this mindset is essential for good engineering. However, steps must be taken to prevent it from spiralling into a vortex of negativity.</p><p>Additionally, the continuous delivery concept is not contributing much to this cause either; major version releases are becoming obsolete.</p><p>While our approach has served Qubit well, there’s a problem. Engineers are not just emotionless robots. We are all a bit human too. Not celebrating success or major milestones eventually makes us feel unappreciated. After all we are a startup, and the golden days of dot-com startups were full of parties.</p><p>To address all of these issues, rather than celebrating launches, we now celebrate the retirement of old products, features and systems.</p><p>Completely shutting a system off means that we’ve either built a better product and migrated all of the users and data onto it or we got rid of unused features that required maintenance (good riddance).</p><p>Focusing only on celebrating the launches leads us to a position where we have to support many legacy versions and to accrue a lot of technical debt. Retiring products proves to be a productivity booster and enables us do things 10x better. Not having lots of technical debt on an old stack also is a great improvement in morale since no self-respecting engineer likes working on shitty old code/features.</p><p>On the horizon there are many depreciation parties I am looking forward to. I cannot wait to put the products ad systems in question to rest and have tombstones for each one of them on our walls so we can fondly remember our past and keep looking forward to the future; it’ll be our way of respectfully commemorating each milestone as we replace our existing products and technologies with the latest and greatest in order to keep up in the global technology race.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf58ee0f5cc1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/qubit-engineering/celebrating-the-dead-projects-bf58ee0f5cc1">Celebrating the dead (projects)</a> was originally published in <a href="https://medium.com/qubit-engineering">Qubit Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tagged Template Strings are a thing]]></title>
            <link>https://medium.com/qubit-engineering/tagged-template-strings-are-a-thing-e284d56b3a40?source=rss----a1e5a35d34d7---4</link>
            <guid isPermaLink="false">https://medium.com/p/e284d56b3a40</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[David Padbury]]></dc:creator>
            <pubDate>Thu, 04 Feb 2016 16:52:34 GMT</pubDate>
            <atom:updated>2016-02-04T16:52:07.749Z</atom:updated>
            <content:encoded><![CDATA[<p>We have so many new features in ES2015+ that now I seem to be forgetting them.</p><p>I was recently throwing together a little node microservice that was heavily utilising some rather fancy sql via <a href="http://knexjs.org/">knex</a>. Although the builder that knex offers is pretty handy, I had a few complex queries that required almost always dropping down into using <a href="http://knexjs.org/#Raw-Queries">knex.raw</a> to write raw sql statements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0134ba9a1004c749da211732e533971/href">https://medium.com/media/a0134ba9a1004c749da211732e533971/href</a></iframe><p>This all works fine; however, with a larger number of parameters making sure that you’ve correctly lined up the question marks in the statement to the values supplied in the following array becomes quite a pain. (Yes, I could have just dropped down to using the <a href="https://github.com/sidorares/node-mysql2#named-placeholders">named params in mysql2 module</a>, but everything else in the app was using knex so I didn’t).</p><p>Template Strings in ES6, the things that give us nice expression interpolation, have (afaik) a little-used advanced form which allows modifying the result of a template string with a function. Lifting the example straight from the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings#Tagged_template_strings">MDN section on tagged template strings</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/149238f1e6154386acaba47be3345f6c/href">https://medium.com/media/149238f1e6154386acaba47be3345f6c/href</a></iframe><p>Effectively prefix the template string with a function name, and that function will get passed an array of strings for each portion of text, and an array of evaluated expressions to do something with.</p><p>With this, the text I need for the sql statement can simply be created by joining the array of strings with a question mark for the parameter placeholders, and the values themselves come in the order I need to place in the array for knex.raw. Doing that is as simple as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f74f9cea2eb9613ace97ae5f11508c1/href">https://medium.com/media/1f74f9cea2eb9613ace97ae5f11508c1/href</a></iframe><p>This can then be used by either passing in a knex instance, or a <a href="http://knexjs.org/#Transactions">transaction that also has a raw method</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f4af71f3324987f09222e24761303e4/href">https://medium.com/media/3f4af71f3324987f09222e24761303e4/href</a></iframe><p>So yeah, tagged template strings are a thing, and with just a couple of lines of code can do pretty useful things.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e284d56b3a40" width="1" height="1" alt=""><hr><p><a href="https://medium.com/qubit-engineering/tagged-template-strings-are-a-thing-e284d56b3a40">Tagged Template Strings are a thing</a> was originally published in <a href="https://medium.com/qubit-engineering">Qubit Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Remoteness Work Part 1: The Video Portal, aka DaveTV]]></title>
            <link>https://medium.com/qubit-engineering/making-remoteness-work-part-1-the-video-portal-aka-davetv-9a3d2a64dd27?source=rss----a1e5a35d34d7---4</link>
            <guid isPermaLink="false">https://medium.com/p/9a3d2a64dd27</guid>
            <category><![CDATA[qubit]]></category>
            <category><![CDATA[remote-working]]></category>
            <dc:creator><![CDATA[David Padbury]]></dc:creator>
            <pubDate>Wed, 02 Dec 2015 12:04:52 GMT</pubDate>
            <atom:updated>2015-12-02T12:06:26.094Z</atom:updated>
            <content:encoded><![CDATA[<p>I joined <a href="http://eng.qubit.com/">Qubit’s engineering department</a> based in London a couple of months ago. The challenge is, I live 4000 miles away in sunny Wisconsin, USA. I’m the first person at Qubit to remote work entirely from the get-go, and so have been experimenting with different ways to start making distributed teams work for us. In this post, I want to talk about our Video Portal setup, which has been a big part in supporting me being on a team nearly a quarter of the way around the world.</p><p>I’ve already had a fair amount of experience with remote teams. I used to manage a number of development teams who were split between cities, client locations, and occasionally people working from home. However, I was always the one in the office. In 6 years, I only worked from home once, because a hurricane had made travelling impossible. I really like going into an office — it puts me in a place where I can focus and then switch off easily when I leave. So although I was confident that these setups can work, being remote felt pretty daunting.</p><p>I spent my first few weeks in London getting to know everyone and trying to understand how Qubit works as an organization. As we started thinking about how our team would work with me being remote, I felt a little awkward having to explain that my biggest fear was simply being a bit lonely. I’d really enjoyed my time sitting alongside the team and would miss the dozen of social touchpoints you inevitably have with people you’re in close proximity to. This started a discussion about how we could make it feel like i’m in the London office while I’m in Wisconsin.</p><p>I remembered a <a href="http://www.hanselman.com/blog/VirtualCamaraderieAPersistentVideoPortalForTheRemoteWorker.aspx">blog post that Scott Hanselman</a> about one of the approaches he used when working remotely. His solution was to have screen on a desk in Redmond with a feed of him working from home. We thought this was a cool idea and so decided to implement it.</p><h4>The Video Portal</h4><p>Sat on my desk in the London office is a monitor which displays a video stream of me working from home in Wisconsin (nicknamed DaveTV). It projects back to me a video feed of the office so I can see the whole team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*vxEivfzceNPz0hZT." /><figcaption>My side in Wisconsin</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*SMFeaHcAB8yxO2js." /><figcaption>DaveTV in London</figcaption></figure><p>I’ve been stunned at quite how well this works. Video conferences are great for formal meetings, but this captures the the informal stuff. I hear the sighs as a colleague’s deployments fail. As another gets up to leave he tells me how his wedding plans are going. When a strategist drops by to randomly grill the team on how far we can push our product, I get to chime in. I’d never set up a formal meeting to discuss this stuff, but because I’m virtually hanging around the office I’m involved in it. It’s this stuff that builds working relationships and makes a team close knit.</p><p>It’s incredible quite how good a substitute it’s been to being there. I can literally just say “<em>Hey Oli — what’s up with [x]?</em>” as if we were sitting together and he responds. Due to wide angle of the camera, I can also see the other teams I occasionally work with and know who’s at their desk or if they’ve got up to go to get a coffee.</p><p>Best of all, it’s actually proved to be a tool for meeting people beyond my team. As my portal is positioned at the end of a row of desks, everyone that walks by it notices it. I meet a couple of new faces everyday who stop to ask what the portal is and start chatting as a result.</p><p>There are strange moments. Being able to yell across the London office from Wisconsin still feels weird. The strangest are perhaps the times I’ll be chatting with the team by our desks when we notice it’s time to do a formal team meeting. They’ll go downstairs and by the time they arrive, I’m already being displayed on our Chrome for Meetings box. It has a somewhat omnipresent-ish feeling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*Q4oNeS0u6zQeJrjp." /><figcaption>Rubber band fights aren’t a common occurrence. Honest.</figcaption></figure><p>As a testament to quite how well it works, it also introduces the downsides of office working. Some noisy construction that lasted a couple of days ended up being just as frustrating for me as those in the office. When Karolis decides to throw rubber bands at James and the office descends into anarchy, I get just as distracted as everyone else. But it’s these things that make me one of the team.</p><h4>Acknowledging the Creepy Factor</h4><p>I have been a little surprised by the reception of the video portal beyond my own team. A number of people who stopped by said they’d find having this video feed from their home a bit creepy. Personally, these thoughts didn’t even occur to me. Being on camera all the time doesn’t feel particularly different from sitting in an office where people can see you. But perhaps this setup isn’t for everyone.</p><p>One of the more practical challenges about always being visible is that people assume I’m always available because they can see me. This can be confusing when I’m actually attending a video meeting on my main computer and am not available to chat. I’ve tried to fix this by really over communicating what I’m up to. Now before every meeting, I’ll update my status in Slack with a “/me attending planning meeting for 45 minutes” and will mute my side of the portal.</p><h4>The Setup</h4><ul><li>Machines — I think it’s vital to have dedicated machines. This way you’ll never cover up the video with another app or have to deal with inevitable restarts. Also, Hangouts is quite a CPU hog; doing anything else on the machine could prove pretty challenging. Importantly, I have a dedicated screen that sits on the very far right of my desk. This way it’s not particularly distracting, but I can just about see it out of the corner of my eye and will notice if someone wonders up to “me” in London.</li><li>Google Hangouts — we’ve tried a few video conference services (Skype and others) but always ended up back on Hangouts. As we use it for our more formal meetings, everyone’s used to it and it works just fine. To make joining it easier, we’ve set up a year long calendar event that comes with a Hangout — joining is only a click away.</li><li>USB Speakerphone — We’ve found getting a decent speakerphone makes an enormous improvement in hearing one another. They seem to be able to amplify people trying to talk to me while minimizing background noise. They also have a hardware mute button, which is really handy — I can just hit it when going into other meetings rather than have to click around the Hangouts UI.</li><li>Webcam — We got a webcam with a fisheye lens for the machine in the office. This way from where I sit I can see the majority of the engineering teams. Most cameras seem to sell themselves on ridiculously high resolutions, but it’s really not important and it’s much easier on bandwidth if the content isn’t super HD.</li><li>Ethernet — I’ve got a pretty reasonable consumer type wifi at home, but my always-on video feed seemed to push it to its limit and occasionally stutter or disconnect. I purchased some adapters to do a wired ethernet setup and found it much more reliable.</li></ul><h4>Thinking with Portals</h4><p>We were so happy with how the portal setup worked for me that we’ve now set up similar screens for other remote staff. It will be interesting to see how far we can run with this. The thought of just having rows of desks with portals rather than physical people sounds like something from a sci-fi film, but at the rate we’re going, it may be a reality sooner rather than later.</p><p>One area I’d like to improve is looking at other ways of having a dedicated machine. I’m currently using my personal MacBook Pro to display things on my side, which isn’t a particularly good use of an expensive machine. I want to look at trying a Raspberry Pi to see how well it’ll support hangouts, which at $35 would be a much cheaper way of dedicating a machine to this purpose. Also, I may look at wall mounting a medium-sized flat monitor to display the office so the portal doesn’t take up any desk space.</p><p>Overall, I feel like it’s gone a long way to helping me feel like being part of the team. Despite going to my home office in Wisconsin, it feels very much like going to work and sitting down alongside everyone. I’ll still be visiting London occasionally to hangout with people in person, but now when I’m not there, I still feel very connected. Perhaps the biggest testament to it’s success is that I arrived in London this week — I have no backlog of chats to have and no significant meetings we’ve been holding off on until I was here. It’s just business as usual.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a3d2a64dd27" width="1" height="1" alt=""><hr><p><a href="https://medium.com/qubit-engineering/making-remoteness-work-part-1-the-video-portal-aka-davetv-9a3d2a64dd27">Making Remoteness Work Part 1: The Video Portal, aka DaveTV</a> was originally published in <a href="https://medium.com/qubit-engineering">Qubit Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easily testing React components with react-test-tree]]></title>
            <link>https://medium.com/qubit-engineering/easily-testing-react-components-with-react-test-tree-f9e1668b1c2d?source=rss----a1e5a35d34d7---4</link>
            <guid isPermaLink="false">https://medium.com/p/f9e1668b1c2d</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[James Hollingworth]]></dc:creator>
            <pubDate>Wed, 20 May 2015 14:59:30 GMT</pubDate>
            <atom:updated>2015-05-20T14:59:30.476Z</atom:updated>
            <content:encoded><![CDATA[<p>While I love React, testing React components leaves a lot to be desired. The <a href="https://facebook.github.io/react/docs/test-utils.html">TestUtils</a> are useful but don’t have a particularly intuitive API and lead to verbose tests, e.g.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2ee24a172d74bebcb2eaa8992a83e79/href">https://medium.com/media/d2ee24a172d74bebcb2eaa8992a83e79/href</a></iframe><p>We’ve been working on a library at <a href="http://qubit.com/">Qubit</a> (<a href="https://qubit.workable.com/jobs/6746?utm_source=jhollingworth&amp;utm_campaign=jhollingworth_blog">We’re hiring</a>) called <a href="https://github.com/QubitProducts/react-test-tree"><strong>react-test-tree</strong></a> which removes a lot of the pain with testing React components.</p><p>It does this by creating an object that represents the given component with an API designed for testing. If you want to make assertions on an element in your component, all you need to is add a <a href="https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute">ref</a> and it will be exposed for testing. Rather than having to simulate events, we give you simple functions (e.g. .click()) to call instead.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e306b2e1c88eccae437f7b5aad23a5b/href">https://medium.com/media/0e306b2e1c88eccae437f7b5aad23a5b/href</a></iframe><p>So what about if I’ve got a collection of elements? We introduce a new attribute, refCollection, which you must add to the parent element. Any children will be available as an array on the test tree.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd80d2182bfb2036df1ec158bad49463/href">https://medium.com/media/cd80d2182bfb2036df1ec158bad49463/href</a></iframe><p>Often when you’re writing your tests you want to prevent certain parts of the component from being rendered e.g. if that part isn’t relevant to the test. React introduced <a href="https://facebook.github.io/react/docs/test-utils.html#shallow-rendering">shallow rendering</a> in v0.13 however we’ve found its rather limited, not allowing the fine grained control we desired. react-test-tree provides a different approach, allowing you to stub refs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55a363835986e60331bf54dc7e9ca201/href">https://medium.com/media/55a363835986e60331bf54dc7e9ca201/href</a></iframe><p>Another thing we often found ourselves doing was passing values down through the <a href="https://www.tildedave.com/2014/11/15/introduction-to-contexts-in-react-js.html">context</a> (e.g. if you want to mock <a href="https://github.com/rackt/react-router">react-router’s</a> router) . This is again trivial with react-test-tree, all you need to do is pass your context object in via the childContext option.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b522fdc3a752385fa733ad21072652d/href">https://medium.com/media/9b522fdc3a752385fa733ad21072652d/href</a></iframe><p>We’ve found react-test-tree is a massive help in testing react components. Theres always room for improvement so would love to hear <a href="https://github.com/qubitproducts/react-test-tree/issues">what you think</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9e1668b1c2d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/qubit-engineering/easily-testing-react-components-with-react-test-tree-f9e1668b1c2d">Easily testing React components with react-test-tree</a> was originally published in <a href="https://medium.com/qubit-engineering">Qubit Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>