<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ahmet Soormally on Medium]]></title>
        <description><![CDATA[Stories by Ahmet Soormally on Medium]]></description>
        <link>https://medium.com/@asoorm?source=rss-6a004b640baa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*NI7NCVpwd60oIF91</url>
            <title>Stories by Ahmet Soormally on Medium</title>
            <link>https://medium.com/@asoorm?source=rss-6a004b640baa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:24:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@asoorm/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Tyk: the API manager you want, need and deserve]]></title>
            <link>https://medium.com/@asoorm/tyk-the-api-manager-you-want-need-and-deserve-31b847273bc?source=rss-6a004b640baa------2</link>
            <guid isPermaLink="false">https://medium.com/p/31b847273bc</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[platform-engineering]]></category>
            <category><![CDATA[api-management]]></category>
            <category><![CDATA[api-gateway]]></category>
            <dc:creator><![CDATA[Ahmet Soormally]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 09:01:46 GMT</pubDate>
            <atom:updated>2023-08-10T12:00:19.930Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/934/0*phEZ5eSLJ7x2iSdx.png" /></figure><p>Evaluating API management vendors for your next project is often complex.</p><p>Every vendor offers an opinion. We offer opinions, too. But here’s the truth: <strong>we want to help you see why our product best fits your needs</strong>. That means we’re biased, however objective we aim to be… but we try!</p><p>Don’t rely solely on a vendor’s feature comparison page. Do your research and gather your evidence. Some of the points made on comparison pages can be seen as positive or negative, depending on your use-case or viewpoint, and they rarely keep up-to-date with the changing conditions of the market.</p><p>At Tyk, we don’t resort to scare tactics or belittling our competitors. We aim to find the overlap of your needs with our capabilities so that you can achieve your desired outcome. Take us for a test run and explore the entire product at your own pace without any sales pitch. If you need assistance, we’re here to guide you in making your own assessment.</p><p>Additionally, we have created a valuable guide to help you <a href="https://tyk.io/blog/how-to-run-an-efficient-evaluations/">evaluate API management vendors</a> and select the best platform for your needs.</p><p>To get you started, here are some areas where Tyk shines…</p><h3>Tyk is simple to install</h3><p>The full enterprise Tyk stack can be installed with just <a href="https://tyk.io/docs/tyk-self-managed/install/">two commands</a> — it cannot get easier than this.</p><p>Additionally, Tyk offers unmatched flexibility, from fully open source, self-managed, consumed as a SaaS, or somewhere in between with a <a href="https://tyk.io/blog/res-api-management-architectural-and-deployment-patterns-101/">hybrid approach</a>.</p><p>Whether you need to deploy Tyk to a constellation of satellites orbiting Earth or a fleet of ocean-going ships, or perhaps you need to power an entire country’s banking system, Tyk has you covered. Sure, the installation gets a bit more complex in these scenarios, but that’s exactly how Tyk is used — check out our <a href="https://tyk.io/case-studies/">case studies</a>.</p><p>Databases, yes, they make things a little more complex at scale… but they enable scale. We’re yet to see any DB-less alternative offering distributed rate limiting, quota management, credential management, and clustering across availability zones and regions with some centralised control.</p><p>We offer quite a bit of flexibility here, too — because Tyk can quite happily run with NoSQL with MongoDB or SQL such as Postgres, MySql, MariaDB — or even Cockroach as per your team preference.</p><h3>Tyk has a large, active and growing open source community</h3><p>Firstly, community size is irrelevant when it comes to resolution time or quality of product. That said, Tyk’s community is large, vibrant and growing. Tyk’s open source project has around 10k stars on GitHub which grows by a steady 10% year-on-year. Tyk’s community forum receives on average 30 new questions per month — which all get responded to within our internal SLA of 48 hours. There is a reason Tyk is rated #1 on G2, and Gartner Peer Insights for customer satisfaction.</p><h3>Tyk works with your service mesh</h3><p>Service mesh is important to many of Tyk’s customers. In a 2022 CNCF survey (biassed to the cloud-native community), 47% of respondents use service mesh within their organisation.</p><p>According to an older 2020 CNCF survey, the leading service mesh is Istio, with 47% market share. LinkerD and Consul tied at 41% market share each — some organisations utilise multiple mesh technologies which is why the percentages go over 100%.</p><p>We believe the combination of API Management from Tyk with an industry leading service mesh from the likes of Istio, LinkerD or Consul is the ideal combination and a far better option than locking into a proprietary “me too” offering by any API management vendor.</p><p>Service mesh is a subset of API management. The reason separate products exist, is that both API management and service mesh require optimised solutions for specific purposes. North/South vs East/West. The market for service mesh also is less mature, a prime example being the evolution of service mesh to a sidecarless architecture.</p><p>Here’s an article on <a href="https://tyk.io/blog/how-does-tyk-work-with-a-service-mesh/">using Tyk API Management with Istio</a>.</p><h3>Tyk offers best in-class governance capabilities</h3><p>Since 2016, Tyk has been delivering API Management for some of the world’s largest banks, telcos and governments. The governance capabilities we’ve developed have resulted from close collaboration with the requirements of those clients.</p><p>Tyk has a native, embedded, Open Policy Agent engine for all administrative APIs. This is unique in API Management and means that Tyk Governance and Authorization support is arguably best-in-class.</p><p>Policy within Tyk is expressed in a high-level, declarative language (REGO), which promotes safe, performant and fine-grained controls. Open Policy Agent is a Graduated CNCF project by Styra, which you can find out more about <a href="https://www.cncf.io/projects/open-policy-agent-opa/">here.</a></p><p>Tyk has had a separate control-plane and data-plane since its inception, meaning that the hybrid deployment option has been available for Tyk customers since 2016. Tyk’s multi-region and hybrid modes are advanced, mature, battle-tested and particularly well suited to core API platform engineering teams who require governance in agile and <a href="https://tyk.io/blog/res-api-management-architectural-and-deployment-patterns-101/">federated API Management capabilities</a>.</p><h3>Tyk Gateway has advanced customisation capabilities</h3><p>Tyk gateway has an embedded Javascript, Python and Lua interpreter. This facilitates the creation of middleware and custom plugins, and even virtual endpoints which enables serverless-like functionality.</p><p>In addition, we support plugin authoring using Tyk’s native language, Go, for ultimate performance and even any language which supports gRPC for ultimate governance and flexibility.</p><p>That said, you won’t need to customise Tyk too much because 95% of what you will need to do will be available out of the box. You see, <strong>Tyk is Open Source</strong>. There are no strings attached; we are not open core, and we don’t have any paid-for plugins.</p><p>With our open source licensing model, our community users are never faced with a paywall — they get exactly the same features and functionality as our paying customers. What’s more, the same plugins work irrespective of your deployment topology — whether Full-SaaS, Hybrid or Self-Managed.</p><h3>Tyk makes automation trivial</h3><p>Tyk is the only API Management solution which utilises the Open API Specification as its native API definition format.</p><p>Import your OAS, make changes, and export again, seamlessly integrating with your PlatformOps, APIOps, GitOps, DevOps, and *Ops workflows.</p><p>With traditional Git workflows, you can utilise Tyk Sync to help you synchronise and migrate between environments, or even deploy it within your CI/CD pipelines.</p><p>In the following 5-minute demo, you can see how Tyk Sync makes it trivial to <a href="https://www.youtube.com/watch?v=HffwIS_YILk">automate Tyk, using Gitea and Jenkins</a> as part of your CI/CD workflow.</p><p>In Kubernetes, you might prefer a declarative approach. <a href="https://www.youtube.com/watch?v=8QCPNZgYp0k">In this short video</a>, you can see how Tyk Operator enables you to package your API configurations, security policy, documentation, and even create API products using Kubernetes custom resources. That’s right, you can package your Tyk CRDs with your regular microservice helm deployments — and it really is that simple.</p><p><a href="https://techblog.realtor.com/api-management-with-federated-autonomy-using-tyk-operator/">In this blog</a>, one of our customers, Realtor.com, talks about how Tyk enables federation and automation at scale.</p><h3>Tyk is lightweight, fast and scales reliably</h3><p>Tyk consistently benchmarks as one of the fastest solutions on the market.</p><h4>Lightweight</h4><p>Consuming just 50 MB in disk space and just 20 MB of RAM at rest means that Tyk is super light and can be (and is!) deployed almost anywhere.</p><h4>Fast</h4><p>Our benchmarks demonstrate that for vanilla HTTP requests, a single gateway can handle in excess of 85k transactions per second whilst introducing just 1.4ms of latency at the 99th percentile. On a commodity $30 per month t2.medium AWS EC2 instance, a Tyk gateway can still comfortably handle <a href="https://tyk.io/performance-benchmarks/">6.5k transactions per second</a>. If you enable auth, rate limits, quotas as well as capture request analytics, and Tyk can still process in excess of 65k transactions per second.</p><h4>Scales reliably</h4><p>We have many clients processing tens or even hundreds of thousands of transactions per second. They achieve this by horizontally scaling their fleets. Having multiple smaller instances of Tyk Gateway provides the added benefit of introducing resilience to the whole cluster.</p><p>Speed isn’t everything, though. A drag racer can go fast in a straight line, but it can’t do much else. Try turning a corner or drive further than the drag strip without running out of fuel or avoiding a crash.</p><p>Tyk Gateways have been designed to load thousands of APIs concurrently, each with tens, hundreds and thousands of endpoints. Aside from policy enforcement, such as authentication, authorization, and analytics, the gateway also processes different kinds of traffic profiles. This ranges from hundreds or thousands of connected clients, long-running connections like Kafka topics, websockets and GraphQL subscriptions and long-poll through to your regular short-lived http request/responses.</p><p>All the above happens concurrently and fluidly within your API ecosystem, while being hot-reloaded as new APIs and policies are created, updated and deleted without negatively impacting your API consumers. Tyk gateway can do all these things and more in the most demanding of environments for the most demanding of customers.</p><p>Don’t just take my word for it — check out this <a href="https://docs.google.com/document/d/1zi8vttkG516sVze9vSeZFOgKrIq9HSLoEf1bR2l2qgY/edit#heading=h.4c6r4mursyhw">short demonstration</a> of Tyk operating at 1M transactions per second:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPZPSJORWMfc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPZPSJORWMfc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPZPSJORWMfc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/abca8cd70caef225e4ecff29d2315c40/href">https://medium.com/media/abca8cd70caef225e4ecff29d2315c40/href</a></iframe><h3>Your partner in API management</h3><p>We are committed to providing fair, unbiased guidance to help you make informed decisions. We want to assist you in finding the right solution for your project, even if it’s different from ours.</p><p>Keen to take Tyk for a test run? Get in touch — we would love to hear about your use-case.</p><p><em>Originally published at </em><a href="https://tyk.io/blog/res-api-management-vendor-comparisons/"><em>https://tyk.io</em></a><em> on August 10, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31b847273bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API management architectural and deployment patterns 101]]></title>
            <link>https://medium.com/@asoorm/api-management-architectural-and-deployment-patterns-101-4c2e13af5e5a?source=rss-6a004b640baa------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c2e13af5e5a</guid>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[api-architecture]]></category>
            <category><![CDATA[architectural-patterns]]></category>
            <category><![CDATA[api-management]]></category>
            <dc:creator><![CDATA[Ahmet Soormally]]></dc:creator>
            <pubDate>Thu, 28 Apr 2022 08:52:28 GMT</pubDate>
            <atom:updated>2022-04-28T10:08:09.843Z</atom:updated>
            <content:encoded><![CDATA[<p>The chosen architecture for deploying API Management can significantly impact how easy (or otherwise) APIs are to manage and scale as requirements evolve. In this guide, we will look at different architectural deployment patterns for API Management and assess the merits of each, along with any potential drawbacks.</p><p>Requirements around performance, resilience, availability, latency, multi-region deployment and a range of other factors all contribute to decisions over which pattern is the most suitable for a given business. Below, we show how Tyk caters to each of these requirements through a self-managed option that provides outstanding control, a cloud pattern that delivers a high degree of convenience and a hybrid pattern that works as an excellent middle ground.</p><p>If your business is in need of effective API management that is attuned to your organisational needs, working through the details below, will put you in a strong position to identify which API deployment pattern not only suits your use-case for today, but can also adapt for tomorrow.</p><h3>API gateway pattern</h3><p>API gateways are typically deployed as the single entry point to your underlying services for clients that might need to access those services.</p><h3>API gateway benefits</h3><p>From a consumer’s perspective, API gateways are a facade, hiding the complexity of the underlying services / microservices / serverless functions and providing a single point of entry to those services.</p><p>By providing a single set of credentials for a suite of APIs, it can considerably reduce the complexity of maintaining multiple API clients and securely storing and managing those credentials.</p><p>By employing a facade pattern, API gateways provide a backend-for-frontend to ensure an optimal experience for different API clients. E.g. smaller response payloads for IoT and mobile devices vs more detailed responses for desktop devices.</p><p>Gateways typically have the ability to mediate between different API types to provide a uniform frontend irrespective of the underlying protocols used. These might include mediating between synchronous and asynchronous services, such as a GraphQL or REST interface to a Kafka topic.</p><p>From the API producer’s perspective, the humble API gateway has become more and more critical to relieve microservices of implementing cross-cutting concerns. It allows API developers to focus on business logic, as opposed to replicating capabilities including security, logging, monitoring, tracing and caching into each individual service.</p><p>In addition to the above capabilities, gateways can actively fire events and dynamically disconnect certain routes, paths and services through the use of uptime tests, circuit breakers, timeouts, throttling and retries.</p><p>Challenges which will almost certainly be faced by not implementing an API Gateway might include:</p><ul><li>necessity to maintain and update libraries across multiple services</li><li>performance overhead from having a dependency on so much code</li><li>inconsistent logging and monitoring implemented across microservices over time,</li><li>an overall maintenance burden.</li></ul><h3>Tyk API gateway</h3><p>In this minimal deployment topology, only the Tyk gateway and Redis are required. Redis is needed to store credentials along with session metadata, track rate-limits and act as a temporary store for request analytics.</p><p>Much like putting NginX, Envoy, Traefik in front of your services, Tyk gateway is very similar, although Tyk is more specialised for fronting APIs.</p><p>Tyk gateway acts as the policy enforcement point which goes between your API consumers and your upstream services. It ensures that only authenticated and authorised client requests may pass to those services, and enforces rate-limits and quotas. It can check that the upstream services are available, disconnect them when there are problems, and act as a load-balancer to multiple upstream services, validate JWT tokens and perform mediation to mention a few.</p><p>The Tyk gateway runtime configurations are either pre-defined by files, environment variables or can be configured via JSON HTTP API in this minimal setup.</p><p>As an enterprise (licensed) customer, this is the same gateway your team will be using in production. This means that your developers can spin up a minimal and lightweight Tyk gateway as part of their local developer workflow, confident that their development environment will work in exactly the same way as production.</p><p>As an Open Source customer, you can be confident that there is no feature lock-out, the same gateway as used by enterprise clients is the same gateway that you too will be using.</p><p>I also touched on the fact that the gateway sends temporary analytics to Redis. These analytics are consumed by a component called Tyk Pump. Similar in functionality to FluentD, Tyk Pump is responsible for ingesting the analytics in Redis, and distributing them to one or more data sinks. These might include Mongo, Kafka, StatsD, CSV, DataDog, ElasticSearch, Splunk and Logz.io to mention a few. Tyk gateway also exposes a Prometheus metrics endpoint for its own health, performance and load.</p><p>Deploying gateways manually is great for simple, or highly automated use-cases, where an architect has the capability and time to design and deploy and run things precisely the way that they need. You are pretty much left to your own devices to apply your own governance, workflows and patterns. API management solutions can and should help you to level up and take things considerably further. API Management provides a framework and tooling required to help you scale, with support for different stakeholder workflows — not just the engineers and architects, but also business and product folk.</p><p>Tyk Dashboard was developed as a control plane to help you manage your APIs. It exposes a HTTP API and a UI. It introduces various concepts including API design, security policies, API versioning, API cataloguing, APIs as products, role based access control (RBAC), analytics querying and reporting, to mention a few. In the context of deployment patterns though, I would like to speak about three in particular which, when combined, open up a whole matrix of possibilities.</p><h3>High performance and high availability</h3><p>In this deployment pattern, you would deploy replica instances of your gateway behind a load balancer. When the gateways boot up, they connect into the Tyk Dashboard control-plane to dynamically pull in their configurations.</p><p>In terms of the simplest form of high availability, we can ensure that there are at least 2 gateways. If you need to upgrade a gateway, the load balancer can stop sending traffic to the gateway which is being serviced until the newly upgraded version comes back online, then the process happens again for the remaining gateway(s).</p><p>Typically, we find that performance will not be limited by the Tyk gateways, but by the capabilities of the load balancer, your network and the underlying services. That said, under heavy load — say both gateways are at ~80% CPU utilisation — shifting all the traffic from one of the gateways to the only remaining gateway will obviously cause problems for that remaining gateway. If your gateways are under load, you will probably need to think about introducing more gateway instances.</p><p>Tyk gateways are extremely lightweight, introduce sub millisecond latency and can handle in the region of 50k rps with just 8 cores. Tyk gateway instances can horizontally scale according to your requirements. If you have over 10 gateway instances, each running hot at 80% CPU, and one instance is taken out of the load balancer, it’s probably OK as the remaining 9 can handle that little bit more traffic. So typically, the more instances you have, the easier it is to distribute the load across them and the more resilient your setup will be.</p><p>Inside Kubernetes, gateways can be installed as a deployment with a set number of replicas, or using a horizontal pod autoscaler to automatically scale up and down depending on load. Gateways can also be upgraded using the rolling update strategy, where we can also control the minimum number of gateways that should be available at any given time.</p><h3>Gateway sharding</h3><p>Sharding allows different gateway instances to selectively load different sets of APIs. Let’s assume, for simplicity’s sake, that we have two zones in our network — DMZ, and an internal zone. We deploy a gateway cluster to the DMZ and another cluster to the internal zone and apply tags to the gateways appropriately. Now it is possible to make an API publicly or internally available by tagging the API Definition with DMZ or internal.</p><p>In a more complex real-life use-case, one of our banking clients needs to serve APIs to 4 differing service-level tiers. Outage of Tier-1 services will require the CEO to make an appearance on the news as it will cause customer debit cards to fail. Tier-2 is for high-priority / availability / heavy duty services, Tier-3 for commodity — still important but recoverable and lower risk. Finally Tier-4 for stuff that doesn’t really matter. As I’m sure you can imagine, it would be desirable for Tier-1 services to be served by their own dedicated gateways alongside much stricter governance. Conversely, Tier-2 and Tier-3 could possibly share gateways and because we don’t want to stifle innovation — we need to increase speed of delivery and not be a blocker to the business — let’s ship Tier-4 services with a much looser governance. This can all be achieved with gateway sharding.</p><h3>Multi-tenancy</h3><p>Let’s assume that you have three teams each working with Tyk. It is possible to bootstrap three different organisations into Tyk, meaning that each team will have their own logical space with their own developer portal and without sharing any data between them. Team members can belong to one or more teams, meaning that when they log-in, they may choose which workspace they want to enter.</p><p>Additionally, it is possible to manage multiple environments such as staging &amp; production using this multi-tenancy capability. This way, in combination with gateway sharding, you can ensure that staging is as close to production as possible, while ensuring logical isolation of configuration data. In combination with gateway tagging and sharding, it is then possible to neatly promote APIs from staging to production.</p><h3>Cluster and region distributed API management patterns</h3><p>In all the previous examples and use-cases, we haven’t yet mentioned anything about cluster or region distributed workloads, from here on, we will refer to both as distributed API management for brevity. The reasons for distributed API management are vast. Use cases for distributed API management range from technical, to legal, to organisational and business needs. This section touches on a handful of common challenges and use-cases.</p><h3>Servicing API consumers at the edge</h3><p>API consumers aren’t always living on servers with high throughput connections, often, they are consuming your services via a flaky 3G mobile connection. Whilst your underlying API services might be hosted in North America, strategically placing API gateways closer to your consumers in Europe, Asia or Africa will significantly improve their latency and overall experience of the services you provide. It is often useful or necessary to perform API caching at the edge for further performance enhancements.</p><h3>Migrating to the cloud, or cloud hopping</h3><p>There are plenty of reasons why your company might want to migrate from one public cloud platform to another. Whether it be consolidation due to Mergers &amp; Acquisitions, to better alignment of services, improved SLAs and pricing, there are hundreds of different scenarios. Regardless of the reason, over time, it is likely that at some point, your organisation will need to safely move some workloads serving API traffic from one cloud provider to another.</p><h3>Handling network partitions</h3><p>You should never trust the network. What happens when things break? How quickly are you able to recover from a disaster?</p><h3>Compliance, certifications and legal requirements</h3><p>Health Insurance Portability and Accountability Act (HIPAA) APIs are used to interact with services which control access to healthcare systems and typically handle Protected Healthcare Information (PHI).</p><p>The General Data Protection Regulation (GDPR) broadly gives individuals more power over their data with enhanced rights to access, rectify, and erase it, and the ability to freely request the transfer of their information to other platforms.</p><p>With a complex organisation, only a small subset of APIs will likely fall under one of these categories. In addition, if PHI, or Personally Identifiable Information (PII) is redacted from an API response, it will not fall under the rules of HIPAA for example.</p><p>In order to achieve compliance, it is often simpler to isolate the services and teams which hold and transfer protected information, meaning that the blast radius requiring compliance remains small.</p><p>Finally, it is often necessary to keep data within a jurisdiction. This means that it can be useful for a control plane and data plane to be in different geographical locations, particularly if the organisation operates across multiple jurisdictions.</p><h3>API teams</h3><p>This is possibly the most complex use-case. Each organisation has a different management size and structure, and has a different hierarchy. From flat, through to tall, centralised to federated, or somewhere inbetween. These are then often split across products, teams and departments, and often, each works in a slightly different way. This makes best practices for API management extremely difficult to recommend as there is never going to be a one-size fits all solution. By its very nature, a successful API programme is dynamic, it lives and evolves as the organisation grows. This means that what’s the right pattern for an organisation today probably won’t be suitable or scale well for the needs of tomorrow.</p><p>As an API program matures, we might go from purely technical team members through to having business stakeholders. These business stakeholders might include Product Managers, API Designers, Technical Writers, and even DevRel to help train, run hackathons and promote use of the APIs. How would the API management platform appropriately serve the needs of all these stakeholders?</p><p>Often, each API will be owned by a team. A team might own one or more APIs. How to appropriately manage and retain visibility and governance of those APIs across a complex, continually evolving ecosystem of multiple teams and API styles?</p><h3>Tyk multi-region</h3><p>In this deployment pattern, we introduce a new component called Multi-Data-Centre-Bridge, or MDCB for short. MDCB is a microservice application which is deployed alongside Tyk’s dashboard inside a centralised control-plane. Clusters of gateways connect to MDCB via RPC. These gateway clusters can be geographically, or logically remote.</p><h3>Loading API Definitions</h3><p>As per all previous architectural patterns, it is possible to leverage tagging and sharding strategies, along with multi tenancy. This means that from a central dashboard, it now becomes possible to manage APIs irrespective of and across multiple geographies, cloud providers and deployment architectures.</p><p>When you configure an API inside Tyk Dashboard, you have full control whether this runtime configuration goes to the gateway cluster deployed to Kubernetes in AWS US East, or to the bare metal dedicated Gateways you have deployed inside your Data Centre in Singapore, or the local test gateway cluster you have deployed to your local machine.</p><p>Configuration is propagated from the control plane to these remote gateway clusters via RPC. This configuration is then cached in a local Redis cluster. Analytics are also sent via this same RPC channel back to the central control plane.</p><h3>Propagating API Keys</h3><p>API keys are typically issued via some catalogue after a portal developer has created an app and requested a subscription to an API Product. This catalogue typically lives alongside the management control plane right next to the multi data centre bridge. Let’s assume we are not doing anything fancy, and it is Tyk that is issuing API keys, rather than something like a dedicated OAuth2/OpenID Connect solution. Our challenge now is that these API Keys and associated permissions and quotas are centrally managed, but the Gateway clusters are globally distributed.</p><p>The first time a protected API call arrives at a Tyk Gateway, Tyk checks its internal cache, then the shared cluster cache provided by Redis, and finally queries MDCB via RPC in order to validate the API key. MDCB then returns the key, along with permissions to the Tyk Gateway, which then stores the key within its internal cache and cluster cache within Redis.</p><p>When keys or permissions are updated or deleted in that centralised control-plane, events will trigger those remote Gateways to flush their local and cluster caches for that key. Whilst the very first request might introduce a little latency whilst the API key is propagated to the local gateways, subsequent requests arriving at the gateway can be serviced extremely quickly with a local lookup, and other Gateways in the cluster only have to go as far as the local Redis to validate the key. Mechanisms for pre-warming gateway cluster caches with API keys go beyond the scope of this article.</p><h3>Consistency, availability and partition tolerance</h3><p>Tyk’s remote Gateway Clusters offer high availability and partition tolerance. That is, Gateway nodes will remain online even if they cannot communicate over RPC with MDCB. Even if they do not have the most recent API key data, they will still continue processing requests. Once connectivity is restored, any keyspace events which were missed will attempt to reconcile based upon a log of events which will buffer inside MDCB.</p><p>Tyk Gateways can achieve this because they have multiple cache layers, internal and cluster level through Redis. Key events all happen centrally at the control plane, meaning that it is not possible to perform writes or deletes of keys at the local gateways. Gateways are capable of buffering request analytics during that network partition until recovery and eventually drop the analytics after some time to ensure that traffic can keep flowing.</p><h3>API analytics for teams</h3><p>We have touched on analytics previously in this article, but all were in the context of analytics being centralised. That’s great if your entire org is using a single analytics solution, but often, the reality is very different. Team 1 will likely be shipping their analytics to Prometheus, and Team 2 will be using Loggly, whilst Team 3 is heavily utilising Kafka. The API Platform team doesn’t require detailed per-request analytics, only aggregate data to see how the platform is being used. So why should the platform team enforce its will when it can cause friction or act as a blocker to potentially many decentralised teams who have different tooling for their use cases?</p><p>Tyk Gateway clusters can be deployed each with their own sets of analytics pumps. This enables each team to take ownership of not only their gateway clusters ensuring no noisy neighbours, but also ship analytics to their data sink of choice. Pumps can then also send the required aggregate analytics back to the central platform team as required.</p><h3>Tyk Cloud</h3><h3>Fully managed API management</h3><p>Tyk Cloud ultimately provides API management as a managed service. It means that you can operate API management, without having to worry about deployment or maintenance of the underlying infrastructure. What makes Tyk Cloud uniquely powerful, is that it offers the ability to architect that infrastructure according to your needs via a point and click or as Code (IaC) mechanism. Tyk Cloud is also a single tenant SaaS solution, meaning quality of service will not suffer due to noisy neighbours and you can be more confident of increased security in comparison to alternative SaaS solutions.</p><p>Tyk Cloud takes care of management of environments and teams, allowing you to deploy your management plane to a continent of your choice. Once your management plane has been deployed, you can then deploy one or more gateway clusters to that home region, or remote regions as per your requirements.</p><p>Tyk Cloud takes care of auto scaling each of Tyk’s components as necessary to ensure both high reliability and availability.</p><p>Opting for a fully managed SaaS solution can significantly reduce time to market. Cloud instances of the Tyk API management platform can be spun up and upgraded almost instantly in a secure production ready manner, saving the hassle of needing special onboarding and expertise of the Tyk stack. It also removes the requirement to procure hardware or cloud compute, setup, configuration and maintenance.</p><p>When considering a fully managed solution it is worth ensuring that network latency is not going to be an issue for your use case. Since the gateways are provided as a cloud service, there will likely be more latency introduced between gateway and your services, than if you were to self host the gateways in your own infrastructure. This makes SaaS gateways potentially better suited to services you wish to expose for external consumption, rather than for internal microservice communication.</p><p>Already, an API gateway is adding a network hop. A client request might originate in Europe, hit an API gateway in the USA, and be proxied to a service residing in Singapore. With this in mind, it’s also worth considering if you need to deploy your SaaS gateways closer to your consumers, but targeting a DNS which is capable of cleverly routing to the nearest gateways to mitigate any latency issues.</p><h3>Hybrid API management</h3><p>It may not be desired for regulatory, performance or security reasons for certain API traffic to leave an API provider’s infrastructure. Hybrid API management attempts to address many, if not all of the shortcomings mentioned with SaaS with very few of the tradeoffs. A halfway house between the convenience of fully managed and the control, security and performance that you would get from self-managing. This makes hybrid API management particularly suited to the internal API management and microservice communication use-cases..</p><p>In this topology, Tyk hosts the management and control plane, much like the fully managed solution, but with the key difference being that the customer self-hosts the Gateways. Hybrid gateways are exactly the same as the multi-region gateways, only rather than pointing to the customer’s MDCB to pull their configurations, they point to Tyk Cloud instead.</p><h3>Conclusion</h3><p>Managing APIs goes far beyond picking something that solves a specific problem, deploying it and then letting it run. An API management solution needs to not only support the needs of today, but also be flexible enough architecturally to support the anticipated challenges of tomorrow.</p><p>The decisions you make around the architecture for your API management can set your business up for both short-term and longer-term success. The deployment patterns presented provide prompts and sample use-cases to think about your own requirements and which pattern will work best for your business.</p><p>With so many variables at play — from technological through to people, culture and teams — it’s important to take a step back and define what it is that you need your APIs to achieve. That knowledge can then help to drive your decision-making around deployment patterns.</p><p>If you’re still seeking answers after reading the above, then the Tyk team is here to help. You can speak to us about our self-managed, cloud and hybrid API management options to work out the best way forward for your unique business environment.</p><p><em>Originally published at </em><a href="https://tyk.io/blog/res-api-management-architectural-and-deployment-patterns-101/"><em>https://tyk.io</em></a><em> on April 28, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c2e13af5e5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OAuth2 Token Exchange RFC8693]]></title>
            <link>https://medium.com/@asoorm/oauth2-token-exchange-rfc8693-6302d2172d1d?source=rss-6a004b640baa------2</link>
            <guid isPermaLink="false">https://medium.com/p/6302d2172d1d</guid>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[api-management]]></category>
            <category><![CDATA[oauth2]]></category>
            <dc:creator><![CDATA[Ahmet Soormally]]></dc:creator>
            <pubDate>Thu, 24 Mar 2022 14:53:10 GMT</pubDate>
            <atom:updated>2022-03-24T20:21:35.322Z</atom:updated>
            <content:encoded><![CDATA[<p>The <a href="https://tools.ietf.org/html/rfc8693">OAuth2 Token Exchange 8693</a> RFC defines a protocol for exchanging security tokens from OAuth2 Authorization servers.</p><p>With a rising popularity of micro-service patterns, it’s almost a given that the API you are calling is actually being fronted by a middleware service. Aside from Load Balancers, your API call will likely be passing through an API Gateway like Tyk, rather than accessing the service directly.</p><p>This post presents typical mechanisms for API Gateways to not only authenticate and authorize themselves, but also propagate user information and permissions to the underlying services which require them. It discusses their shortcomings, and then presents how the OAuth2 Token Exchange protocol can mitigate these shortcomings and improve API security overall.</p><h3>OAuth2 is a delegation protocol</h3><p>OAuth is a delegation protocol. Each actor has their own own separate identity. In this ridiculously simplified diagram, we can see several actors: Alice, an App, Browser and the API. In OAuth2 speak, they are known as the Resource Owner, User Agent, Client Application and Resource Servers respectively. When Alice wants to perform any operation with her personal data, the API can’t just blindly return that data to the App. Rather, there is a protocol by which Alice needs to identify and authenticate herself, then delegate some of her rights to the App. The app also has its own identity, so once it has authenticated itself, it may then act as an agent on behalf of Alice.</p><p>When the App sends a request to the API to request Alice’s personal data, it does so using a bearer token. This token can be a reference or self-contained token, the details are not so important for the purposes of this post, but let’s assume that this token contains some claims including the id of the App and also Alice’s user id. This is great, because for as long as there is a mechanism for the API to validate the authenticity of this token, and can therefore trust this metadata, then it can effectively make a decision as to whether it may perform some protected operation on Alice’s data.</p><h3>Introducing an API Gateway complicates things</h3><p>Once you got your head around the protocols and the flows — we are off to the races — but not so fast… It’s never that simple. We have an API Gateway deployed right in the middle between the App and the API in order to protect that API from abuse. By introducing the Gateway how does the API know who is logged in?</p><p>Let’s break this down a little into a few different strategies:</p><h3>Auth Proxy</h3><p>One way in which we can achieve this, is by trusting the Gateway implicitly, then transparently passing the Apps access token through to the API directly. I guess it kind of works, but…</p><p>The Access token contains an audience claim (aud), which specifies who this access token is intended to be read by. This can either be the App, or the Gateway, but not both. Now in the Auth Proxy scenario, the Gateway effectively is acting as a Man in the Middle, and is trusting an access token which was not intended for it.</p><p>If the API became or is directly accessible by the App, then it means that the same access token used on the Gateway can also be used directly on the API. This means that the Gateway can relatively easily be bypassed and presents a potential attack vector, without extra mitigating layers of security.</p><h3>OAuth2 Client Credentials</h3><p>In this flow — we are considerably more secure. The Gateway has its own credentials to access the API. The API knows to only trust traffic coming via the Gateway as the Gateway will be using its own access token. If any request arrived to the API, or the API were to accidentally be made public, still, only the Gateway would be able to access any protected data.</p><p>The problem here however is that regardless whether Alice logged in, or Bob is logged into the app, the Gateway is always using its own credentials to access the API.</p><p>This means several things. Firstly, the Gateway can validate the access token presented by the App. Once it has done that, it can use its own credentials to proxy the request on to the API. The API has to grant the Gateway almost superuser privileges to perform any operation on any user. Why, because it becomes impossible to propagate Alice’s userID and her delegated permissions to the App through to the API. This information is lost and by the time the request gets to the API, the API will not even know who the logged in user is. If Alice was an Employee, and Bob a Manager, this means that Alice could potentially give herself a pay rise FTW!</p><p>If we wanted to propagate user and role information to the API, ensuring that only Alice could access her own data, we would need to extract the UserID and role information or delegated permissions from the App’s Access Token, then use the Gateway to inject this information as some magic request headers in the request to the API. The API would then need to be modified or coded to read these headers, in order to apply this business logic. This is a pattern which many Gateways and other solutions recommend, as the Gateway is now having to perform some level of business logic. The Gateway would also need to be programmed to remove this magic header — as it could potentially be possible for the App to inject that header before it even got to the gateway, presenting potentially another attack vector.</p><p>I could go through a bunch of other tactics / strategies, but… Let us fast forward a bit to the point of this post. I hope that you all get that there has not really been a solid and scalable solution for effectively what is a pretty complex problem…</p><h3>OAuth2 Token Exchange</h3><p>In this flow — everything is exactly the same for the Gateway using the Client Credentials flow, as the Gateway has its own identity.</p><p>The difference however is that when the Gateway authenticates (exchanges its credentials for a bearer token) with the authorization server, it also passes a bunch of other fields as part of the request.</p><pre>grant_type: &quot;urn:ietf:params:oauth:grant-type:token-exchange&quot; subject_token: &quot;ORIGINAL_APPS_ACCESS_TOKEN&quot;</pre><p>Rather than a client_credentials grant, it is invoking a urn:ietf:params:oauth:grant-type:token-exchange grant. And passing the access token presented by the App along with the request. That means that when Alice uses an App to request her data, and Bob uses an App to access his data, the Gateway will obtain a unique token for each request.</p><p>In the following snippet, you will find a sample request from the Gateway to the Authorization server.</p><pre>POST /token </pre><pre>grant_type: &quot;urn:ietf:params:oauth:grant-type:token-exchange&quot; <br>code: &quot;a130cb70-af3c-44f6-a030-779b042cfaec.a5e5796a-0c99-4b5b-bf62-19fb7ea20ec3.8be6e388-cc31-441c-9b88-386c74ae2381&quot; <br>client_id: &quot;gateway&quot; <br>client_secret: &quot;GATEWAY_CLIENT_SECRET&quot; <br>subject_token: &quot;APP_ACCESS_TOKEN&quot;</pre><p>This means that the Gateway obtains it’s own access token for each logged in user. The Gateway becomes the authorized party, And it’s permissions (scopes) are dynamic, based on the permissions of the user who logged in. Let’s take a look at the metadata for the Gateway’s Access Token for the API.</p><pre>{ <br>  &quot;exp&quot;: 1606174134, <br>  &quot;iat&quot;: 1606173834, <br>  &quot;auth_time&quot;: 1606173730, <br>  &quot;jti&quot;: &quot;7368999a-0b78-47c5-abcb-1dc5a59b649d&quot;, <br>  &quot;iss&quot;: &quot;https://MY.OPENID.ISSUER&quot;, <br>  &quot;aud&quot;: &quot;api&quot;, &lt;---- 1 <br>  &quot;sub&quot;: &quot;57e7837a-c490-4d80-91d5-723e92ff6ebe&quot;, <br>  &quot;typ&quot;: &quot;Bearer&quot;, <br>  &quot;azp&quot;: &quot;gateway&quot;, &lt;---- 2 <br>  &quot;acr&quot;: &quot;1&quot;,<br>  &quot;resource_access&quot;: { <br>    &quot;account&quot;: { &lt;---- 3 <br>      &quot;roles&quot;: [ <br>        &quot;manage-account&quot;, <br>        &quot;manage-account-links&quot;, &quot;view-profile&quot; <br>      ] <br>    } <br>  }, <br>  &quot;scope&quot;: &quot;profile email&quot;, &lt;----- 4 <br>  &quot;email_verified&quot;: true, <br>  &quot;name&quot;: &quot;Alice&quot;, <br>  &quot;preferred_username&quot;: &quot;<a href="https://tyk.io/cdn-cgi/l/email-protection">a</a>lice@example.com&quot;, &lt;----- 5 <br>  &quot;given_name&quot;: &quot;Alice&quot;, <br>  &quot;email&quot;: &quot;<a href="https://tyk.io/cdn-cgi/l/email-protection">a</a>lice@example.com&quot; <br>  }</pre><p>1. The API can validate that the access token was intended for its consumption<br> 2. The API can validate that this token is coming from the Gateway and it has not been bypassed<br> 3. The API can validate that Alice has delegated her permissions and these have been propagated to the Gateway<br> 4. The API can validate the scopes which were delgated by Alice also<br> 5. The API can identify that it is Alice who is the logged in user</p><h3>Conclusion</h3><p>In conclusion, I believe that this is an extremely elegant way of utilising the OAuth2 Framework to propagate identity and permissions securely through a chain of different actors, and if adopted by API Gateways, goes a long way toward standardising API Authentication and Authorization mechanisms.</p><p>If the OAuth2 Token exchange is a protocol you are currently using, or are interested in, please do get in touch, I would love to hear from you.</p><p><em>Originally published at </em><a href="https://tyk.io/blog/oauth2-token-exchange-rfc8693/"><em>https://tyk.io</em></a><em> on March 24, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6302d2172d1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL: A platform approach]]></title>
            <link>https://medium.com/@asoorm/graphql-a-platform-approach-358c155baebc?source=rss-6a004b640baa------2</link>
            <guid isPermaLink="false">https://medium.com/p/358c155baebc</guid>
            <dc:creator><![CDATA[Ahmet Soormally]]></dc:creator>
            <pubDate>Mon, 15 Jun 2020 19:58:48 GMT</pubDate>
            <atom:updated>2020-08-12T21:06:04.052Z</atom:updated>
            <content:encoded><![CDATA[<p>Tyk is excited to announce <a href="https://tyk.io/features/graphql/">Universal Data Graph</a> — a powerful addition to Tyk’s open-source API Gateway &amp; Enterprise Management Platform. Universal Data Graph enables API Product,Managers &amp; Developers alike, to leverage all the benefits and power of GraphQL, with none of the drawbacks.</p><p>GraphQL encourages best-practices like thinking about the design of your API prior to implementation. It gives other benefits such as strong typing and living documentation. But whose responsibility is it to manage, maintain and evolve the GraphQL API?</p><p>Front-End teams often own the GraphQL endpoint for their applications. The GraphQL server is typically a facade to underlying backend services. Effectively a niche backend-for-frontend, but providing flexibility for the consumers. Whenever there needs to be a slight change in the request / response structure, the frontend developer no longer needs to ask a backend developer for help they simply change the query — and move on. Unfortunately, this also makes front-end developers responsible for the security and management of the API.</p><p>Handing responsibility of the GraphQL endpoint to the backend teams, means tight coupling and deep coordination between front-end and backend in order to maintain and manage the schema.</p><p>Universal Data Graph facilitates the creation of the API Platform. Where front-end developers may focus on the consumption of the API services and their front-end application business logic — back-end developers can focus on their underlying services — whether greenfield, REST, gRPC or GraphQL.</p><p>We can now introduce the role of the API Product Manager, who can be responsible for nurturing the GraphQL API, creating fine-grained security policies &amp; plans which can prepare the API for discovery, public consumption, subscription &amp; monetization, alongside a traditional REST API if desired — Arming GraphQL with tried and tested API Management security and full lifecycle management capabilities.</p><p>Let’s take this step by step and show how Tyk is working to make this a reality.</p><h3>GraphQL an initial Approach</h3><p>So you are sold on GraphQL — how might you go about hooking up a REST API for example?</p><p>Step 1: Design &amp; Implement your GraphQL schema</p><p>Step 2: Connect your data-sources</p><p>Step 3: Write Query &amp; Mutation Resolvers</p><p>Step 4: Ship to production!</p><p>Easy right? I’m pretty sure we’re missing something…</p><p>Unfortunately — Alongside these considerations — Learning how to consume a GraphQL API is considerably easier than it is to author. Where does authentication, authorization, query validation, normalization &amp; complexity based rate limiting belong in a GraphQL API?</p><h3>GraphQL Authentication</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/0*DBj7tXdMXpgienEK.png" /></figure><p>Out of the box, Tyk enables you to protect your GraphQL API with the full-authentication capabilities that ship with Tyk’s gateway.</p><p>This includes JWT, OAuth2, Static Tokens and even Mutual TLS.</p><p>Changing auth mechanisms, or migrating between auth mechanisms becomes a managed process — with zero code and can be achieved with zero downtime for your customers.</p><p>And if you need to integrate with a non-standards based authentication mechanism, you can always write a plugin in your language of choice.</p><h3>GraphQL Authorization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/0*UoNVjwv6Rg8gCgQW.png" /></figure><p>Building this out further. How do we deal with Internal versus External APIs? Whilst GitHub publish their entire Graph, I’m sure that we don’t see the entire schema.</p><p>Tyk approaches this by putting Authorization logic at the Gateway Security Policy level. By placing the gateway as the policy enforcement point, it means you have to write less repetitive boilerplate in each of your backend services. You can easily choose with a point and click whether to expose a particular query, mutation, type or field to the graph.</p><p>Different API consumers get different access rights. Connect or disconnect an entire type, field or field from the graph on a per-client or client-group basis — all at the click of a button.</p><p>The screenshot above illustrates a configuration of a security policy that disabled the People type entirely &amp; removed access to the height field inside the Person type. A different client group might have more permissive access to the graph.</p><h3>GraphQL DoS Attack Protection</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/0*Uh1gEaANeAJ0BE_I.png" /></figure><p>It is trivial to launch a denial-of-service attack on a GraphQL server. GraphQL does not define best-practices in terms of limiting Query Complexity, and as such, early implementations of GraphQL servers catching the hype cycle either don’t think about these things, or have done so as an afterthought.</p><p>As such, I could query a GraphQL API with infinite complexity — or just enough complexity to bring down a server (intentionally or accidentally).</p><p>But this doesn’t just apply to these deeply nested queries — it also applies to complex graphs which might resolve to multiple data sources.</p><p>Some options that have been suggested in the past for solving this problem include: restricting query size (raw bytes); query whitelisting, or even query depth limiting.</p><p>A great library commonly in-use these days to solve the query-depth problem alone might be something like <a href="https://github.com/stems/graphql-depth-limit">https://github.com/stems/graphql-depth-limit</a>. You will still need to pull in other libraries to help you solve some other problems in the list, so this library only solves a niche use-case for NodeJS specifically. We are introducing tight coupling of the GraphQL server &amp; require a developer to write code &amp; re-deploy whenever changes need to be made. You need to be able to write your own logic, or find a suitable library in your language of choice.</p><p>What if you need to enable some clients to send deeper queries than others? An Internal team should be able to perform more expensive operations than the general public. And if I have multiple paid subscription plans for my GraphQL API, Such as Gold, Silver, Bronze and a Free Plan, then the Free plan definitely needs to be more restrictive than one of the paid plans, and a lower tier might be more restrictive than an SLA or Gold tier plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/0*NSN2Hf-pcUfs5euw.png" /></figure><p>Tyk solves this problem at the Security Policy layer which allows you to change the allowable depth of a query on a per-key, or per security policy basis.</p><h3>Developing &amp; nurturing the Graph with no code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/0*dF6d3S37LPpNXtae.png" /></figure><p>In addition to the security aspects — we still need to write our GraphQL resolvers in our language of choice. And we still need to solve the problem of whose responsibility it is to hook up all these services, nurture them and bring them to production.</p><p>In more traditional API management workflows, this would be the responsibility of the API product manager or API designer, rather than a backend or frontend engineer. They would define the authentication &amp; authorization modes, how to protect the service, versioning &amp; general lifecycle management strategy. They would typically be the glue between the backend engineers who design the services &amp; the frontend engineers (whether internal, external or partners) who consume the services.</p><p>Tyk has developed a novel approach for GraphQL which facilitates this exact workflow.</p><p>Backend developers can focus on building their services in their infrastructure, language and protocol of choice. There is no need to rewrite existing services to support GraphQL.</p><p>The API Designer &amp; Product Manager: designs the GraphQL Schema (via a point-and-click gui or schema editor); hooks up the data-sources from an existing API managed by Tyk, or a 3rd party API (REST &amp; GraphQL supported — more data-sources coming soon); applies security policies &amp; publishes the Graph to the developer portal.</p><p>The consumers of the GraphQL API — whether that be a front-end developer writing their next mobile or web application can consume the GraphQL API without having to worry about the underlying stack &amp; without having to be responsible for the security or access control for the Graph.</p><p>When an API call is made, Tyk’s execution engine will handle all the stitching, resolving &amp; composition automatically. And because this was all configured with a point and click — you end up with a manifest which you can use to migrate configurations between environments. It becomes repeatable.</p><p>Every time you write code, there is a responsibility for; maintenance; bug fixes; issues etc.</p><p>Tyk’s no-code approach significantly reduces technical debt and applies tried and tested Security and Full Lifecycle Management capabilities to your new data graph. This allows you to get the job done by focusing on solving business problems. Whilst Tyk’s API Gateway takes care of Integration, mediation &amp; security in a similar fashion that has been solved in a manner which you are all used to in the REST world.</p><h3>Help us build the future</h3><p>There is plenty more coming, and lots more to develop &amp; evolve, from: adding more data-sources; detailed analytics; performance enhancements &amp; further security capabilities — All in the name of enabling you to confidently navigate your GraphQL API to production.</p><p>Whether you are looking for a unified GraphQL wrapper to compose your services, build a GraphQL ingress to your service mesh or simply looking to protect an existing GraphQL API — we want to hear from you. Tyk’s GraphQL Engine is built directly into our open-source API Gateway with no feature lock-out. Help us to build the future of the Universal Data Graph, from ideas, enhancements &amp; even code — Welcome to the journey of the Universal Data Graph.</p><p><em>Originally published at </em><a href="https://tyk.io/graphql-a-platform-approach/"><em>https://tyk.io</em></a><em> on June 15, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=358c155baebc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[go-bench-suite: A mock server for testing your proxy / gateway]]></title>
            <link>https://medium.com/@asoorm/go-bench-suite-a-mock-server-for-testing-your-proxy-gateway-36dc102355d?source=rss-6a004b640baa------2</link>
            <guid isPermaLink="false">https://medium.com/p/36dc102355d</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[benchmarking]]></category>
            <category><![CDATA[tyk]]></category>
            <dc:creator><![CDATA[Ahmet Soormally]]></dc:creator>
            <pubDate>Fri, 17 Apr 2020 23:31:48 GMT</pubDate>
            <atom:updated>2020-04-23T14:48:00.110Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introducing go-bench-suite a mock upstream to test your proxy / gateway</h3><p>Whilst running some tests to ensure that <a href="https://tyk.io/">Tyk’s Open Source Gateway </a>remains performant in different scenarios, I found that I needed an ultra fast backend microservice which could take tens of thousands of RPS without a sweat.</p><p>I was a bit tired of hitting a static NginX page or a httpbin.org endpoint, where I couldn’t simulate slightly more complex scenarios, or problems in the underlying services. The reality is that services rarely perform as they do in a sanitary environment. A synthentic benchmark is completely unrealistic, but that’s not to say you can’t get a good idea about how your systems will react if you can synthesise a little chaos.</p><p>Hence, <a href="https://github.com/asoorm/go-bench-suite">go-bench-suite</a> was born.</p><p><a href="https://github.com/asoorm/go-bench-suite">asoorm/go-bench-suite</a></p><p>Why call it go-bench-suite? Well I’m not particularly original — it’s written in Go, and it offers a suite of endpoints to help me bench. :D</p><blockquote>Disclaimer:</blockquote><blockquote>The purpose of the benchmarks performed in this post. are to introduce <strong>go-bench-suite</strong> and <strong>hey-hdr</strong>.</blockquote><blockquote>The tests in this post have been run in a completely unsanitary environment on a fully-loaded laptop. Take the numbers with a pinch of salt.</blockquote><blockquote>I would expect different numbers on production machines in a sanitary environment.</blockquote><blockquote>I have definitely not performed any tuning or config changes to the proxies benchmarked in in this post. Do not take this as an assumption that one proxy is faster or better than another. It is not the purpose of this post.</blockquote><p>Back to business:</p><p>So what exactly can go-bench-suite do anyway? Well in it’s most simple use-case, it can return a valid JSON response, it can do a lot more, but I’ll just highlight a few cool things.</p><p>First, the hello-world of go-bench-suite: Get the the current time:</p><pre>curl <a href="http://localhost:8000/json/valid">http://localhost:8000/json/valid</a><br>{&quot;time&quot;: &quot;2020-04-17 21:05:34.100646 +0000 UTC m=+211184.687113588&quot;}</pre><h3>Mocking upstream latency by setting a delay</h3><p>But that’s not so interesting. Let’s simulate a very slow upstream.</p><pre>echo &quot;$(date)\n&quot; &amp;&amp; curl localhost:8000/json/valid -H &#39;X-Delay: 2s&#39; -i &amp;&amp; echo &quot;\n$(date)\n&quot;<br>Fri 17 Apr 2020 22:10:28 BST</pre><pre>HTTP/1.1 200 OK<br>Server: fasthttp<br>Date: Fri, 17 Apr 2020 21:10:30 GMT<br>Content-Type: text/plain; charset=utf-8<br>Content-Length: 69</pre><pre>{&quot;time&quot;: &quot;2020-04-17 21:10:30.7301232 +0000 UTC m=+211481.663253888&quot;}<br>Fri 17 Apr 2020 22:10:30 BST</pre><p>As you can see, go-bench-suite returned its response in 2s. go-bench-suite supports different units for the delay. Valid time units are ns, us (or µs), ms, s, m, h .</p><p>This is particularly useful, if you know that your service response time is 200ms for example, and you need to see how the proxy(s) in-front of your service can handle multiple connections being open for quite a long time.</p><h3>Introducing some Chaos</h3><p>Realistically, some endpoints perform well most of the time, but occasionally for some reason, or other, response time is particularly slow — maybe ElasticSearch is indexing at the time, or some database cluster is having issues. We can mock this by injecting a little chaos.</p><pre>hey -H &#39;X-Delay: 3s&#39; -H &#39;X-Delay-Percent: 5&#39; <a href="http://localhost:8000/json/valid">http://localhost:8000/json/valid</a></pre><pre>Summary:<br>  Total: 3.0328 secs<br>  Slowest: 3.0207 secs<br>  Fastest: 0.0014 secs<br>  Average: 0.2030 secs<br>  Requests/sec: 65.9453</pre><pre>Total data: 13778 bytes<br>  Size/request: 68 bytes</pre><pre>Response time histogram:<br>  0.001 [1] |<br>  0.303 [186] |■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■<br>  0.605 [0] |<br>  0.907 [0] |<br>  1.209 [0] |<br>  1.511 [0] |<br>  1.813 [0] |<br>  2.115 [0] |<br>  2.417 [0] |<br>  2.719 [0] |<br>  3.021 [13] |■■■</pre><pre>Latency distribution:<br>  10% in 0.0028 secs<br>  25% in 0.0042 secs<br>  50% in 0.0052 secs<br>  75% in 0.0161 secs<br>  90% in 0.0202 secs<br>  95% in 3.0009 secs<br>  99% in 3.0053 secs</pre><pre>Details (average, fastest, slowest):<br>  DNS+dialup: 0.0009 secs, 0.0014 secs, 3.0207 secs<br>  DNS-lookup: 0.0006 secs, 0.0000 secs, 0.0027 secs<br>  req write: 0.0000 secs, 0.0000 secs, 0.0002 secs<br>  resp wait: 0.2020 secs, 0.0013 secs, 3.0163 secs<br>  resp read: 0.0000 secs, 0.0000 secs, 0.0002 secs</pre><pre>Status code distribution:<br>  [200] 200 responses</pre><p>X-Delay is set to 3s, and X-Delay-Percent is set to 5. This means that approximately 5% of all requests will take 3s, whilst the rest should be super fast. I’ve used rakyll/hey here to demonstrate.</p><p>But why is this useful? Let’s assume that I have 2 backend servers behind a load-balancer, and one of them is playing up. So that means 50% of responses are slow. I can handle 10 connections. I send 200 requests. The slow server will be queueing up those requests.</p><pre>hey -H &#39;X-Delay: 3s&#39; -H &#39;X-Delay-Percent: 50&#39; -c 10 <a href="http://localhost:8000/json/valid">http://localhost:8000/json/valid</a></pre><pre>Summary:<br>  Total: 42.0631 secs<br>  Slowest: 3.0057 secs<br>  Fastest: 0.0013 secs<br>  Average: 1.6224 secs<br>  Requests/sec: 4.7548</pre><pre>Total data: 13770 bytes<br>  Size/request: 68 bytes</pre><pre>Response time histogram:<br>  0.001 [1] |<br>  0.302 [91] |■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■<br>  0.602 [0] |<br>  0.903 [0] |<br>  1.203 [0] |<br>  1.503 [0] |<br>  1.804 [0] |<br>  2.104 [0] |<br>  2.405 [0] |<br>  2.705 [0] |<br>  3.006 [108] |■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■</pre><pre>Latency distribution:<br>  10% in 0.0019 secs<br>  25% in 0.0028 secs<br>  50% in 2.9991 secs<br>  75% in 3.0019 secs<br>  90% in 3.0045 secs<br>  95% in 3.0049 secs<br>  99% in 3.0056 secs</pre><pre>Details (average, fastest, slowest):<br>  DNS+dialup: 0.0001 secs, 0.0013 secs, 3.0057 secs<br>  DNS-lookup: 0.0001 secs, 0.0000 secs, 0.0019 secs<br>  req write: 0.0000 secs, 0.0000 secs, 0.0004 secs<br>  resp wait: 1.6221 secs, 0.0013 secs, 3.0055 secs<br>  resp read: 0.0001 secs, 0.0000 secs, 0.0003 secs</pre><pre>Status code distribution:<br>  [200] 200 responses</pre><p>As can be seen, in this example, despite 100 requests taking 3 seconds, we have strangled how many requests the server can handle. As such, it took a total of 42 seconds to respond to 200 requests.</p><h3>Mocking Request &amp; Response Body</h3><p>In more realistic scenarios, you can expect your API to accept POST data, and the message body is probably going to be bigger than a couple of characters.</p><p>Let’s assume I want to mock a 1kb response from the server</p><pre>curl -s -X GET localhost:8000/size/1KB<br>rMreyaFRgstBVAYLzhhTpuqXyDEMtPQmJCaqKuOXXCGnhpmshbaWClCJxsSGagmxluBdAaFnKOWVFeElwqsoNvUFrNuVaOjjloCcIHgOFtMtQoQvoGwnKRxFeUcNzDjTdqCAlXLZofewqckqBOOksLbrliqMHJntXkNZZCSJdCJYolVmsFchXsVGtYYvPpTBsysJKhuJwYwYpwgtxSqesXaiGwJZdBiCTJTlZesrEPFyLVTFSVoLRylmTyAPUjsBLGDOJPQcntfVCUTnqhxhHZpsLLnDGskGRVenqTvGfGLFPTBaRxVcVANgarIyXYNZJsuAitFIDiRCNegabDQEtlKfuRxSYyYjGeOZyVEZMgTjIBzkwpGYJKCqzntsSPISGPQVXQBFjxWuGKYeQjGffHRJaJcAyTzDaioaUKeEKVTWpcnFuxydMiiOCPNPeBxuFiHooVnashVMSvhPhEwmRzbHVLDgdESMIZlhMymceiLzzobWhhvGvpBGsfDpppbtnSnAZBzTEjDZukCUddvjbauWqTaqkqNIQAGfcYqQHJUkShwmNfSVCfPRlyiqdIEyzslAYmYeszsIYbrHRGSIqQSHpgJYMkxZebvIyTkCbAFqNqRcnnVgOxONNKYxDfYjnCYxwGKSrBSQfnwzFITLzrJAlzoeEJXLaZahtKycdPiUSMpugFVwOCAljHlYQzNKEVJFBHqeBSUmOzgRVTnjqCLcgxbIJKNhcCPuvxBHwiOmdLNnygSwizHHXZkqGzgnIIohxMPztgiMvRJSOWhNcazaFTsyNcOdFuHsPqmuPxjhNWgoXTRBWeEgRnVKIHDtvbgIsKpbLqsliEOHxijZTzWCPdMlEAtpbuKsCwlpBZxyMFiczRohGpMNacKnkxSpJnzPGRVLKtOlDVcYdFspQyibwUiPEucNKnryJSFffECgmFaxTSozQCptfGpgusYuXwLoZvBMjCNlpoiduPUGtPMaqZwXFqCPZlBDLVFRIjanLsnNCUZxqlFfVuDTrWzX</pre><p>go-bench-suite just returned to me a 1KB response of random characters. I can apply a delay as before &amp; inject a bit of chaos to slow it down for more complex scenarios.</p><p>But what if the server also accepts data?</p><pre>curl -X POST -d &quot;$(curl -s -X GET localhost:8000/size/5KB)&quot; localhost:8000/size/20B -i<br>HTTP/1.1 100 Continue</pre><pre>HTTP/1.1 200 OK<br>Server: fasthttp<br>Date: Fri, 17 Apr 2020 21:42:26 GMT<br>Content-Type: text/plain; charset=utf-8<br>Content-Length: 20</pre><pre>AskGGHgQgMITByYodfGh</pre><p>In this example, I’ve posted 5KB to the upstream, and the upstream has responded with 20B.</p><h3>What about non-json / random characters? My upstream returns XML!</h3><pre>curl <a href="http://localhost:8000/xml">http://localhost:8000/xml</a><br>&lt;?xml version=&#39;1.0&#39; encoding=&#39;us-ascii&#39;?&gt;<br>&lt;!--  A SAMPLE set of slides  --&gt;<br>&lt;slideshow title=&quot;Sample Slide Show&quot; date=&quot;Date of publication&quot; author=&quot;Yours Truly&quot;&gt;<br>  &lt;!-- TITLE SLIDE --&gt;<br>  &lt;slide type=&quot;all&quot;&gt;<br>    &lt;title&gt;Wake up to WonderWidgets!&lt;/title&gt;<br>  &lt;/slide&gt;</pre><pre>&lt;!-- OVERVIEW --&gt;<br>  &lt;slide type=&quot;all&quot;&gt;<br>    &lt;title&gt;Overview&lt;/title&gt;<br>    &lt;item&gt;Why &lt;em&gt;WonderWidgets&lt;/em&gt; are great&lt;/item&gt;<br>    &lt;item/&gt;<br>    &lt;item&gt;Who &lt;em&gt;buys&lt;/em&gt; WonderWidgets&lt;/item&gt;<br>  &lt;/slide&gt;<br>&lt;/slideshow&gt;</pre><p>go-bench-suite shamelessly stole the XML response from the excellent httpbin service!</p><h3>So what’s all this got to do with benchmarking proxies?</h3><p>Well first of all, we can hit the server directly to get a baseline, and pipe the output to my <a href="https://github.com/asoorm/hey-hdr">hey-hdr</a> library.</p><pre>hey -n 10000 -c 50 -q 20 -o csv <a href="http://localhost:8000/xml">http://localhost:8000/xml</a> | hey-hdr -out baseline.xml<br>  Count: 10000<br>    Max: 21.7ms<br>   Mean: 7.706ms<br>    P50: 7.7ms<br>    P95: 11.3ms<br>    P99: 13.7ms<br>   P999: 20.7ms<br>  P9999: 21.5ms<br> P99999: 21.7ms</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*PwgqNGsOv9TorgEvJJmyOQ.png" /><figcaption>Baseline Latency Scatter Plot</figcaption></figure><p>Let’s configure NginX installed via homebrew to transparently proxy to our upstream server.</p><pre># nginx.conf<br>events{}</pre><pre>http {<br>    upstream bench {<br>        server 127.0.0.1:8000;<br>    }</pre><pre>server {<br>        listen 9999;<br>        location / {<br>          proxy_pass <a href="http://bench/">http://bench</a>;<br>        }<br>    }<br>}</pre><p>Output of the benchmark:</p><pre>hey -n 10000 -c 50 -q 20 -o csv <a href="http://localhost:9999/xml|">http://localhost:9999/xml|</a> hey-hdr -out nginx_transparent2.xml<br>  Count: 10000<br>    Max: 71.403ms<br>   Mean: 24.752ms<br>    P50: 24.6ms<br>    P95: 35.601ms<br>    P99: 41.401ms<br>   P999: 51.601ms<br>  P9999: 55.601ms<br> P99999: 71.403ms</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*J8wwVOQXl9nen_LTTWHfzQ.png" /><figcaption>NginX Latency Scatter Plot</figcaption></figure><p>We also configure Tyk gateway to transparently proxy to the go-bench-suite server and once again, pipe the output to hey-hdr</p><pre>hey -n 10000 -c 50 -q 10 -o csv <a href="http://localhost:8081/xml">http://localhost:8081/xml</a> | hey-hdr -out tyk_transparent.xml<br>  Count: 10000<br>    Max: 27.4ms<br>   Mean: 8.576ms<br>    P50: 8.4ms<br>    P95: 12ms<br>    P99: 15.5ms<br>   P999: 25.3ms<br>  P9999: 27.1ms<br> P99999: 27.4ms</pre><p>And finally, let’s do something cool. We will configure an API in Tyk to transform the XML response to JSON, and change the Content-Type header from application/xml to application/json.</p><pre>curl -s <a href="http://localhost:8081/bench/xml">http://localhost:8081/bench/xml</a> | jq<br>{<br>  &quot;slideshow&quot;: {<br>    &quot;-author&quot;: &quot;Yours Truly&quot;,<br>    &quot;-date&quot;: &quot;Date of publication&quot;,<br>    &quot;-title&quot;: &quot;Sample Slide Show&quot;,<br>    &quot;slide&quot;: [<br>      {<br>        &quot;-type&quot;: &quot;all&quot;,<br>        &quot;title&quot;: &quot;Wake up to WonderWidgets!&quot;<br>      },<br>      {<br>        &quot;-type&quot;: &quot;all&quot;,<br>        &quot;item&quot;: [<br>          &quot;Why&quot;,<br>          &quot;&quot;,<br>          &quot;Who&quot;<br>        ],<br>        &quot;title&quot;: &quot;Overview&quot;<br>      }<br>    ]<br>  }<br>}</pre><p>Now we know that Tyk has successfully transformed our response from XML to JSON, let’s benchmark it.</p><pre>hey -n 10000 -c 50 -q 20 -o csv <a href="http://localhost:8081/bench/xml|">http://localhost:8081/bench/xml|</a> hey-hdr -out tyk_transformed3.xml<br>  Count: 10000<br>    Max: 56.201ms<br>   Mean: 24.057ms<br>    P50: 23.8ms<br>    P95: 37.401ms<br>    P99: 44.001ms<br>   P999: 48.601ms<br>  P9999: 55.201ms<br> P99999: 56.201ms</pre><p><a href="https://github.com/asoorm/hey-hdr">hey-hdr</a> has given us a couple of other files aside from the scatter plots. Let’s pass all three through an HDR Histogram plotter to visualise the difference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vuOTO3lGbY2B5d3h_M84hw.png" /><figcaption>Example HDR Histogram Plot</figcaption></figure><p>So in all tests, we sent 10,000 requests with 50 consumers, each consumer sending 20 Requests per second. Making a total of 1000 rps for 10 seconds.</p><p>As a transparent proxy, Tyk Gateway only really appears to add any overhead at P99.5. After that, it’s pretty negligible.</p><p>What’s interesting is that transforming XML to JSON, as expected is a tad slower, but given that Tyk has had to evaluate 1000 XML response bodies &amp; dynamically transcode them to JSON — It’s done a damn good job given that there is no caching involved!</p><p>NginX proxy_pass seems to be performing about as well as Tyk transforming XML to JSON. Something really doesn’t look quite right here though. I tried it like 4 times and got similar results — I’ve probably configured it wrong.</p><blockquote>Disclaimer Repeat:</blockquote><blockquote>The purpose of these benchmarks are to introduce go-bench-suite and hey-hdr.</blockquote><blockquote>These tests have been run in a completely unsanitary environment on a fully-loaded laptop.</blockquote><blockquote>I would expect better / different performance on production machines.</blockquote><blockquote>I have definitely not performed any tuning to NginX or Tyk. So please do not take this as an assumption that one proxy is faster than another.</blockquote><p>Would welcome you to have a play with hey-hdr and go-bench-suite, and let me know what you have created with it. Feel free to file/fix bugs and contributions are more than welcome.</p><ul><li><a href="https://github.com/asoorm/hey-hdr">asoorm/hey-hdr</a></li><li><a href="https://github.com/asoorm/go-bench-suite">asoorm/go-bench-suite</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36dc102355d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[rakyll/hey Load Testing — extended with HDR]]></title>
            <link>https://medium.com/@asoorm/rakyll-hey-load-testing-extended-with-hdr-1500aa262411?source=rss-6a004b640baa------2</link>
            <guid isPermaLink="false">https://medium.com/p/1500aa262411</guid>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[benchmarking]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[hey]]></category>
            <category><![CDATA[benchmark]]></category>
            <dc:creator><![CDATA[Ahmet Soormally]]></dc:creator>
            <pubDate>Thu, 16 Apr 2020 15:33:23 GMT</pubDate>
            <atom:updated>2020-04-16T20:04:44.464Z</atom:updated>
            <content:encoded><![CDATA[<h3>rakyll/hey Load Testing —enhanced with HDR</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*seH1VFi__rHXTXcXbMq3OA.png" /></figure><p>I’ve played with quite a lot of load testing tools out there; they all have their pro’s, con’s and frustrations. Despite all the power, features and capabilities, I always find myself going back to the rather excellent rakyll/hey load testing tool.</p><p>It’s simple, efficient, performant, powerful, and was designed as a more modern alternative to Apache’s AB. Why ever look elsewhere one may ask? Well the answer for me is that the summary output, whilst very cool, is a little too simplistic for my use-case.</p><p>To illustrate, I will run a quick test against a mock upstream I created go-bench-suite. <a href="https://github.com/asoorm/go-bench-suite">https://github.com/asoorm/go-bench-suite</a></p><pre>docker run --rm -itd --name bench -p 8000:8000 mangomm/go-bench-suite ./go-bench-suite upstream</pre><p>Now let’s run hey against it</p><pre>hey <a href="http://localhost:8000/json/valid">http://localhost:8000/json/valid</a></pre><pre>Summary:<br>  Total: 0.0402 secs<br>  Slowest: 0.0247 secs<br>  Fastest: 0.0020 secs<br>  Average: 0.0089 secs<br>  Requests/sec: 4981.1345</pre><pre>Total data: 13765 bytes<br>  Size/request: 68 bytes</pre><pre>Response time histogram:<br>  0.002 [1] |<br>  0.004 [26] |■■■■■■■■■■■<br>  0.007 [97] |■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■<br>  0.009 [26] |■■■■■■■■■■■<br>  0.011 [0] |<br>  0.013 [0] |<br>  0.016 [0] |<br>  0.018 [1] |<br>  0.020 [28] |■■■■■■■■■■■■<br>  0.022 [13] |■■■■■<br>  0.025 [8] |■■■</pre><pre>Latency distribution:<br>  10% in 0.0038 secs<br>  25% in 0.0047 secs<br>  50% in 0.0060 secs<br>  75% in 0.0178 secs<br>  90% in 0.0202 secs<br>  95% in 0.0212 secs<br>  99% in 0.0235 secs</pre><pre>Details (average, fastest, slowest):<br>  DNS+dialup: 0.0012 secs, 0.0020 secs, 0.0247 secs<br>  DNS-lookup: 0.0006 secs, 0.0000 secs, 0.0031 secs<br>  req write: 0.0000 secs, 0.0000 secs, 0.0002 secs<br>  resp wait: 0.0076 secs, 0.0019 secs, 0.0185 secs<br>  resp read: 0.0001 secs, 0.0000 secs, 0.0006 secs</pre><pre>Status code distribution:<br>  [200] 200 responses</pre><p>A few things which bother me:</p><ol><li>Why are there 50 responses that came back within 20ms, when the vast majority or responses were sub 10ms? Now just for the record, 20ms isn’t really slow, but it is a bit worrying when the vast number of calls are super fast.</li><li>The granularity of our percentile latencies P99 just isn’t enough. The reality is that 1 in 99 requests, when you are receiving 5k rps (pretty normal these days), means that every second, 30 requests will experience a slow response time. Now imagine a single web page load generates requests for 100 supporting assets. And assuming that some of these are XHR requests — meaning that we are querying some API. Then you have a service mesh in-place, meaning proxying through a scary maze of microservices. What I’m trying to say is that this equates to potentially every single user getting a less than acceptable experience.</li></ol><p>This inspired me to dig a little deeper into what I can do with hey to get a little bit more meaningful output that allows me to visualise with a little more granularity what is going on.</p><p>I found that you can output the raw metrics from Hey to a CSV dump.</p><pre>hey -o csv <a href="http://localhost:8000/json/valid">http://localhost:8000/json/valid</a><br>response-time,DNS+dialup,DNS,Request-write,Response-delay,Response-read,status-code,offset<br>0.0171,0.0067,0.0039,0.0002,0.0095,0.0006,200,0.0041<br>0.0170,0.0066,0.0047,0.0000,0.0099,0.0005,200,0.0042<br>0.0170,0.0058,0.0044,0.0000,0.0107,0.0005,200,0.0042<br>0.0197,0.0092,0.0045,0.0000,0.0094,0.0006,200,0.0016<br>0.0169,0.0065,0.0045,0.0002,0.0097,0.0005,200,0.0043<br>0.0198,0.0088,0.0053,0.0000,0.0100,0.0005,200,0.0014<br>0.0171,0.0058,0.0043,0.0000,0.0105,0.0007,200,0.0043<br>0.0172,0.0062,0.0044,0.0000,0.0104,0.0006,200,0.0041<br>0.0198,0.0083,0.0045,0.0000,0.0104,0.0007,200,0.0015<br>--- SNIP ---</pre><p>Now I have far too much detail. The raw data is almost undecipherable and I have no idea how to process this information.</p><p>Introducing Hey-HDR: <a href="https://github.com/asoorm/hey-hdr">https://github.com/asoorm/hey-hdr</a></p><p>Hey HDR is a very simple Extract-Transform-Load script (pretty quickly hacked together), which allows you to pipe the output of Hey into it, and it will re-calculate the histogram buckets to measure a granularity of up to 5 nines. But what it will also do is generate some nice graphs to help you visualise that raw data. let’s run that test again, this time with hey-hdr.</p><pre>hey -o csv <a href="http://localhost:8000/json/valid">http://localhost:8000/json/valid</a> | go run hey-hdr.go -out example<br>  Count: 200<br>    Max: 29.1ms<br>   Mean: 12.904ms<br>    P50: 10.4ms<br>    P95: 26.2ms<br>    P99: 27.9ms<br>   P999: 29.1ms<br>  P9999: 29.1ms<br> P99999: 29.1ms</pre><p>So now we can see more clearly where performance degradation occurs.</p><p>We also get some files:</p><pre>cat example.hdr.csv<br>Value(ms)  Percentile  TotalCount  1/(1-Percentile)<br>0.000      0.000000    0           1.00<br>3.900      0.100000    20          1.11<br>4.700      0.200000    40          1.25<br>6.800      0.300000    60          1.43<br>9.600      0.400000    80          1.67<br>12.500     0.500000    100         2.00<br>13.800     0.550000    110         2.22<br>--- SNIP ---<br>28.800     0.999995    200         200000.00<br>28.800     0.999996    200         250000.00<br>28.800     0.999997    200         333333.33<br>28.800     0.999998    200         500000.00<br>28.800     0.999999    200         1000000.00<br>28.800     1.000000    200         10000000.00</pre><p>Let’s load example.hdr.csv into <a href="http://hdrhistogram.github.io/HdrHistogram/plotFiles.html">HDR Histogram Plot</a> we can now see more easily where performance degradation occurs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFDhhN2VQjHhk6qcJhvwdw.png" /><figcaption>HDR Histogram Plot</figcaption></figure><p>But let’s assume that we did some stuff to speed up our response time, how do we compare visually what the improvement is? Simply by running the tests again, and loading both HDR files into the histogram plotter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*seH1VFi__rHXTXcXbMq3OA.png" /><figcaption>Histogram comparison example</figcaption></figure><p>And finally, we also get a png scatter diagram output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*UfB2ipBB4kOG9OWET5t9Wg.png" /></figure><p>This scatter diagram gives us a clue as to what the problem is — or why 50 requests took so long to respond. Maybe it has to do with the 3-way TCP handshake? Once connections are established, and we are able to re-use them, rather than closing them, performance is noticeably better.</p><p>Hope you found it useful, I would welcome some PR’s and enhancements to</p><ul><li><a href="https://github.com/asoorm/hey-hdr">https://github.com/asoorm/hey-hdr</a></li><li><a href="https://github.com/asoorm/go-bench-suite">https://github.com/asoorm/go-bench-suite</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1500aa262411" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observing API metrics with Tyk, Elasticsearch & Kibana]]></title>
            <link>https://medium.com/@asoorm/observing-your-api-metrics-with-tyk-elasticsearch-kibana-74e8fd946c39?source=rss-6a004b640baa------2</link>
            <guid isPermaLink="false">https://medium.com/p/74e8fd946c39</guid>
            <category><![CDATA[api-management]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[tyk]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[kibana]]></category>
            <dc:creator><![CDATA[Ahmet Soormally]]></dc:creator>
            <pubDate>Sat, 11 Jan 2020 00:50:24 GMT</pubDate>
            <atom:updated>2020-01-13T23:33:54.546Z</atom:updated>
            <content:encoded><![CDATA[<h3>Observing your API traffic with Tyk, Elasticsearch &amp; Kibana</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lsx05kS7XlRTzMtkE_To1g.png" /><figcaption>Simplified architecture diagram of the TEK stack. Tyk, Elasticsearch &amp; Kibana</figcaption></figure><p>You have your backend services for ACME.com built and ready to ship. Something is wrong — it’s Black Friday, and the conversion rate seems unusually low, despite what looks like significant increased traffic. The business is breathing down the engineers necks — money is being lost, and customer helpdesk queries have started piling in. Is the problem with the mobile app, our backend services? are we being attacked, are systems becoming overloaded due to the sheer volume of traffic arriving at the site? Where to start debugging?</p><p>I’m going to show you how you can gain these valuable insights by simply using Tyk as a transparent proxy to your underlying services, and having Tyk ship your API analytics to Elastic Search for viewing &amp; interrogation in a beautiful Kibana dashboard.</p><p>TLDR; Feel free to jump straight into a pre-baked docker-compose <a href="https://github.com/asoorm/tyk-elasticsearch-kibana">https://github.com/asoorm/tyk-elasticsearch-kibana</a></p><p>Or if you are more of a YouTuber, I’ve prepared a walkthrough to accompany this blog post — just scroll to the bottom for the embed.</p><h3>What are Tyk, Elasticsearch &amp; Kibana (TEK Stack)?</h3><blockquote>Did I just invent a name for <strong>yet another</strong> open-source stack???</blockquote><p><a href="https://tyk.io/"><strong>Tyk open source API Gateway</strong></a><strong> </strong>is basically (a reverse proxy or load balancer). Think HA Proxy or NginX, but with a programmable API &amp; purposefully designed for proxying &amp; protecting your API traffic.</p><p>Because Tyk has been designed specifically as an API Gateway, your analytics are context aware — in that they are enriched specifically to provide useful information for your API traffic. Which API version is popular? Are my customers still using that deprecated API? Is it safe to retire my API. Can I capture specific information about the request, and store it with the request logs for later grepping? All this, rather than the simple request log output that you would get with your typical application load-balancer.</p><p>Out of the box, Tyk can also work with your existing Service Discovery tooling such as Consul or etcd to discover you backend services. It offers active healthchecks, uptime tests, enforced timeouts and circuit breakers, which can take unhealthy services out of the balancer, fire events or webhooks to wake up an engineer when things go really wrong or to trigger scaling events. If you need to customise Tyk for any reason to do something on the request path, you don’t need to learn Lua — Tyk offers built in Python, Go, JavaScript &amp; gRPC support.</p><p>We will be working with the gateway <a href="https://github.com/TykTechnologies/tyk">https://github.com/TykTechnologies/tyk</a> and the analytics pump <a href="https://github.com/TykTechnologies/tyk-pump">https://github.com/TykTechnologies/tyk-pump</a>.</p><p>Back to business — the engineer has now been paged, bleary eyed, she opens up her laptop — it’s BlackFriday — and there are literally gigabytes of application logs to cat, grep, awk and cut through. If only there was a simple &amp; efficient way of quickly grepping these metrics?</p><p><a href="https://www.elastic.co/"><strong>Elasticsearch</strong></a> is an Open Core search engine, based on Lucene. It provides distributed, full-text search with a RESTful interface and is an analytics database, capable of ingesting and indexing megabytes of data per second.</p><p><a href="https://www.elastic.co/products/kibana"><strong>Kibana</strong></a> lets you build your own visualisations &amp; dashboards based on this Elasticsearch data.</p><h3>Setting up the TEK Stack</h3><blockquote>DISCLAIMER:<br>This is far from a production setup — we are just quickly getting up and running in a local dev environment using Docker.</blockquote><p>For our backend service, we are going to use the excellent <a href="https://httpbin.org/">https://httpbin.org</a> api. HttpBin has several endpoints which allow us to test pretty much everything we need.</p><pre># example curl request to httpbin.org/get?foo=bar showing response headers and response body</pre><pre>curl <a href="https://httpbin.org/get/?foo=bar">https://httpbin.org/get\?foo=bar</a> -i<br>HTTP/1.1 200 OK<br>Access-Control-Allow-Credentials: true<br>Access-Control-Allow-Origin: *<br>Content-Type: application/json<br>Date: Thu, 09 Jan 2020 08:50:26 GMT<br>Referrer-Policy: no-referrer-when-downgrade<br>Server: nginx<br>X-Content-Type-Options: nosniff<br>X-Frame-Options: DENY<br>X-XSS-Protection: 1; mode=block<br>Content-Length: 232<br>Connection: keep-alive</pre><pre>{<br>  &quot;args&quot;: {<br>    &quot;foo&quot;: &quot;bar&quot;<br>  },<br>  &quot;headers&quot;: {<br>    &quot;Accept&quot;: &quot;*/*&quot;,<br>    &quot;Host&quot;: &quot;httpbin.org&quot;,<br>    &quot;User-Agent&quot;: &quot;curl/7.67.0&quot;<br>  },<br>  &quot;origin&quot;: &quot;151.224.16.210, 151.224.16.210&quot;,<br>  &quot;url&quot;: &quot;<a href="https://httpbin.org/get?foo=bar">https://httpbin.org/get?foo=bar</a>&quot;<br>}</pre><p>We can setup a simple Elasticsearch &amp; Kibana as follows:</p><pre>docker network create es</pre><pre># Start Elasticsearch<br>docker run -it --rm --name elasticsearch --network es -p 9200:9200 -p 9300:9300 elasticsearch:6.8.6</pre><pre># Start Kibana<br>docker run -it --rm --name kibana --network es -p 5601:5601 \<br>  -e ELASTICSEARCH_HOSTS=<a href="http://elastic-search:9200/">http://elastic-search:9200</a> \<br>  docker.elastic.co/kibana/kibana:6.8.6</pre><p>You should now be able to access your Kibana dashboard from your browser on <a href="http://localhost:5601/">http://localhost:5601</a>. There is no data in your Elasticsearch database yet though, so let’s setup Tyk and start shipping some request logs.</p><p>In order to setup Tyk to proxy to our httpbin service, we need a Redis database. Redis is used to store those temporary analytics, api keys &amp; cluster configurations. We will also need Tyk Gateway and Tyk Pump, all of which are available on Dockerhub.</p><p>Tyk Pump is a powerful analytics shipper, which can not only send analytics to Elasticsearch. Tyk Pump also has native integrations with Prometheus, StatsD, Mongo, DataDog, Logz.io, Influx, Kafka— even a CSV file to mention a few. <a href="https://github.com/TykTechnologies/tyk-pump">https://github.com/TykTechnologies/tyk-pump</a>. If you have more complex requirements, you can also send to multiple combinations of data-sinks at the same time.</p><blockquote>There are positives &amp; negatives about having a separate analytics pump. The big positive is separation of concerns — and this means that the pump microservice can independently scale &amp; fail without blocking or causing problems for the gateway request flow. The downside is that you have another service to manage &amp; monitor, but hopefully this blog post will show that configuration is a cinch.</blockquote><p>We will use the following configs for Tyk Pump — It is also possible to configure the pump with environment variables.</p><pre>cat pump.json</pre><pre>{<br>  &quot;analytics_storage_type&quot;: &quot;redis&quot;,<br>  &quot;analytics_storage_config&quot;: {<br>    &quot;type&quot;: &quot;redis&quot;,<br>    &quot;host&quot;: &quot;redis&quot;,<br>    &quot;port&quot;: 6379,<br>    &quot;optimisation_max_idle&quot;: 100,<br>    &quot;optimisation_max_active&quot;: 200,<br>    &quot;enable_cluster&quot;: false<br>  },<br>  &quot;purge_delay&quot;: 5,<br>  &quot;pumps&quot;: {<br>    &quot;elasticsearch&quot;: {<br>      &quot;type&quot;: &quot;elasticsearch&quot;,<br>      &quot;meta&quot;: {<br>        &quot;index_name&quot;: &quot;tyk_analytics&quot;,<br>        &quot;elasticsearch_url&quot;: &quot;http://elasticsearch:9200&quot;,<br>        &quot;enable_sniffing&quot;: false,<br>        &quot;document_type&quot;: &quot;tyk_analytics&quot;,<br>        &quot;rolling_index&quot;: false,<br>        &quot;extended_stats&quot;: false,<br>        &quot;version&quot;: &quot;6&quot;<br>      }<br>    }<br>  },<br>  &quot;dont_purge_uptime_data&quot;: true<br>}</pre><p>Now we can start Tyk Pump whilst mounting the pump configurations.</p><pre>docker network create tyk</pre><pre># create the pump container<br>docker create -it --network tyk --name pump --rm \<br>  -v $(pwd)/pump.json:/opt/tyk-pump/pump.conf \<br>  tykio/tyk-pump-docker-pub</pre><pre># attach the pump to the es network<br>docker network connect es pump</pre><pre># start Tyk Pump<br>docker start pump</pre><pre># follow the logs if we want<br>docker logs --follow pump</pre><pre>[Jan  9 13:20:53]  INFO main: Init Pump: Elasticsearch Pump<br>[Jan  9 13:20:53]  INFO main: Starting purge loop <a href="http://twitter.com/5">@5</a>(s)<br>[Jan  9 13:20:58]  WARN redis: Connection dropped, connecting..<br>[Jan  9 13:21:51]  INFO main: ## Tyk Analytics Pump, v0.8.3 ##<br>[Jan  9 13:21:51]  INFO elasticsearch-pump: Elasticsearch URL: <a href="http://elasticsearch:9200/">http://elasticsearch:9200</a><br>[Jan  9 13:21:51]  INFO elasticsearch-pump: Elasticsearch Index: tyk_analytics<br>[Jan  9 13:21:51]  INFO main: Init Pump: Elasticsearch Pump<br>[Jan  9 13:21:51]  INFO main: Starting purge loop <a href="http://twitter.com/5">@5</a>(s)<br>[Jan  9 13:21:56]  WARN redis: Connection dropped, connecting..</pre><p>Now that we have the analytics part setup &amp; up and running, all we need to do now is create a Tyk API Definition (the thing that tells Tyk what to do), mount it into the Tyk docker container and start the gateway.</p><p>Example API Definition:</p><pre>cat httpbin.json</pre><pre>{<br>  &quot;name&quot;: &quot;httpbin&quot;,<br>  &quot;slug&quot;: &quot;httpbin&quot;,<br>  &quot;api_id&quot;: &quot;httpbin&quot;,<br>  &quot;use_keyless&quot;: true,<br>  &quot;version_data&quot;: {<br>    &quot;not_versioned&quot;: true,<br>    &quot;default_version&quot;: &quot;&quot;,<br>    &quot;versions&quot;: {<br>      &quot;default&quot;: {<br>        &quot;name&quot;: &quot;default&quot;,<br>        &quot;use_extended_paths&quot;: true<br>      }<br>    }<br>  },<br>  &quot;proxy&quot;: {<br>    &quot;listen_path&quot;: &quot;/httpbin/&quot;,<br>    &quot;target_url&quot;: &quot;<a href="http://httpbin.org/">http://httpbin.org/</a>&quot;,<br>    &quot;strip_listen_path&quot;: true <br>  },<br>  &quot;active&quot;: true,<br>  &quot;tag_headers&quot;: [],<br>  &quot;strip_auth_data&quot;: false<br>}</pre><p>We save this API definition document into a directory — say apps, then mount it into the gateway.</p><pre>docker run -it --rm --network tyk --name tyk \<br>  -p 8080:8080 \<br>  -v $(pwd)/apps:/opt/tyk-gateway/apps \<br>  -e TYK_GW_ENABLEANALYTICS=true \<br>  tykio/tyk-gateway:v2.9.2 tyk --conf tyk.standalone.conf</pre><pre>[Jan 09 13:53:59]  INFO main: Tyk API Gateway v2.9.2</pre><pre>&lt;-----snip-----&gt;<br><br>[Jan 09 13:53:59]  INFO Loading API Specification from /opt/tyk-gateway/apps/httpbin.json<br>[Jan 09 13:53:59]  INFO main: Detected 1 APIs<br>[Jan 09 13:53:59]  INFO main: Loading API configurations.<br>[Jan 09 13:53:59]  INFO main: Tracking hostname api_name=httpbin domain=(no host)<br>[Jan 09 13:53:59]  INFO main: Initialising Tyk REST API Endpoints<br>[Jan 09 13:53:59]  INFO main: API bind on custom port:0<br>[Jan 09 13:53:59]  INFO Initializing HealthChecker<br>[Jan 09 13:53:59]  INFO Checking security policy: Open api_id=httpbin api_name=httpbin org_id=<br>[Jan 09 13:53:59]  INFO gateway: API Loaded api_id=httpbin api_name=httpbin org_id= server_name=-- user_id=-- user_ip=--<br>[Jan 09 13:53:59]  INFO host-check-mgr: Loading uptime tests...<br>[Jan 09 13:53:59]  INFO main: Initialised API Definitions<br>[Jan 09 13:53:59]  INFO main: API reload complete</pre><p>Our app has path based routing enabled, but we could have just as easily enabled host-based routing if we wanted to.</p><p>Let’s send a request to the HttpBin service via the gateway, and see what comes back:</p><pre>curl <a href="http://localhost:8080/httpbin/get/?foo=bar">http://localhost:8080/httpbin/get\?foo=bar</a> -i<br>HTTP/1.1 200 OK<br>Access-Control-Allow-Credentials: true<br>Access-Control-Allow-Origin: *<br>Content-Type: application/json<br>Date: Thu, 09 Jan 2020 13:57:52 GMT<br>Referrer-Policy: no-referrer-when-downgrade<br>Server: nginx<br>X-Content-Type-Options: nosniff<br>X-Frame-Options: DENY<br>X-Ratelimit-Limit: 0<br>X-Ratelimit-Remaining: 0<br>X-Ratelimit-Reset: 0<br>X-Xss-Protection: 1; mode=block<br>Content-Length: 272</pre><pre>{<br>  &quot;args&quot;: {<br>    &quot;foo&quot;: &quot;bar&quot;<br>  },<br>  &quot;headers&quot;: {<br>    &quot;Accept&quot;: &quot;*/*&quot;,<br>    &quot;Accept-Encoding&quot;: &quot;gzip&quot;,<br>    &quot;Host&quot;: &quot;httpbin.org&quot;,<br>    &quot;User-Agent&quot;: &quot;curl/7.67.0&quot;<br>  },<br>  &quot;origin&quot;: &quot;172.19.0.1, 151.224.16.210, 172.19.0.1&quot;,<br>  &quot;url&quot;: &quot;<a href="https://httpbin.org/get?foo=bar">https://httpbin.org/get?foo=bar</a>&quot;<br>}</pre><p>Checking the pump logs — we can also see that we have successfully shipped our request analytics to Elasticsearch</p><pre>[Jan  9 13:57:53]  INFO elasticsearch-pump: Writing 1 records</pre><p>And now, all we need to do is visit the Kibana dashboard and do a little setup. We need to create an index pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AWo6yiQUn7yCrkHooaavUA.png" /><figcaption>Defining an index pattern in Kibana</figcaption></figure><p>An index pattern tells Kibana which Elasticsearch indices contain the data that you want to work with. In our example, we only have one index tyk_analytics.</p><p>Once we have created our index pattern, we can; Interactively explore our data in Discover. Analyze our data in charts, tables, gauges, tag clouds, and more in Visualize. Let’s navigate to the Discover page to see our single lonely request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OKrgP5jSoVTgmxlHbRtw-g.png" /><figcaption>Viewing first request proxied through Tyk in Kibana</figcaption></figure><p>Let’s send some more requests so that we can get a slightly better &amp; more realistic visualisation</p><pre>for i in {1..10}; do curl <a href="http://localhost:8080/httpbin/get/?foo=bar">http://localhost:8080/httpbin/get\?foo=bar</a>; done</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qPAlrDVXpQksTSTjhlwGtg.png" /><figcaption>Several Requests proxied through Tyk, passed to Elasticsearch and viewed in Kibana</figcaption></figure><p>And maybe force an internal server error or two</p><pre>curl <a href="http://localhost:8080/httpbin/status/500">http://localhost:8080/httpbin/status/500</a> -i<br>HTTP/1.1 500 Internal Server Error<br>Access-Control-Allow-Credentials: true<br>Access-Control-Allow-Origin: *<br>Content-Length: 0<br>Content-Type: text/html; charset=utf-8<br>Date: Thu, 09 Jan 2020 14:17:08 GMT<br>Referrer-Policy: no-referrer-when-downgrade<br>Server: nginx<br>X-Content-Type-Options: nosniff<br>X-Frame-Options: DENY<br>X-Ratelimit-Limit: 0<br>X-Ratelimit-Remaining: 0<br>X-Ratelimit-Reset: 0<br>X-Xss-Protection: 1; mode=block</pre><p>Then filter our analytics to hunt down those erroneous responses. We can do this by querying response_code:500 for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VbZfW0HnxEpzEz6eLtjJuQ.png" /></figure><p>Querying Elasticsearch for errors which have been generated by Tyk</p><p>We can even build out beautiful aggregate visualisations based on the metrics we sent to Elasticsearch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lmj0keUbDPIQlx24KGAcdw.png" /><figcaption>Example Kibana dashboard src: <a href="https://www.elastic.co/guide/en/beats/metricbeat/current/view-kibana-dashboards.html">https://www.elastic.co/guide/en/beats/metricbeat/current/view-kibana-dashboards.html</a></figcaption></figure><p>I really haven’t scratched the surface of this powerful combination of putting an API Gateway in-front of your services, and shipping analytics to Elasticsearch for viewing in Kibana.</p><p>I don’t personally have the experience of designing Kibana dashboards, but it doesn’t really look too difficult. So I cheated and pasted in a demo example from the Elastic website for some inspiration &amp; get your creative juices flowing.</p><p>Tyk has the ability to inspect payloads, and inject this data into your analytics pipeline, for further analyis later. It’s even possible to record the entire request and response body, and have that indexed by Elasticsearch also.</p><p>Further, you can easily tag your requests using a correlation id, user id, order id or other. Using that, it becomes trivial to track down individual operations and debug what went wrong.</p><p>Pushing the boat out further, we could grab the ip address of the client, and get Kibana to display us acoordinate map to see where on earth our client requests are coming from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cZHqNRm-pEfnXDlGoGmQWQ.png" /><figcaption>Example Kibana coordinate map using geoip lookup</figcaption></figure><h3>Querying analytics based on user Context</h3><p>Let’s attempt one of those slightly more complex &amp; closer to real-life examples to illustrate.</p><p>Create a new directory, at the same level as your apps directory called policies . In this directory add the file policies.json with the following contents.</p><pre>cat policies/policies.json</pre><pre>{<br>  &quot;5e189590801287e42a6cf5ce&quot;: {<br>    &quot;id&quot;: &quot;5e189590801287e42a6cf5ce&quot;,<br>    &quot;rate&quot;: 100,<br>    &quot;per&quot;: 1,<br>    &quot;quota_max&quot;: -1,<br>    &quot;quota_renews&quot;: -1,<br>    &quot;quota_remaining&quot;: 0,<br>    &quot;quota_renewal_rate&quot;: 60,<br>    &quot;access_rights&quot;: {<br>      &quot;httpbin-jwt&quot;: {<br>        &quot;api_id&quot;: &quot;httpbin-jwt&quot;,<br>        &quot;api_name&quot;: &quot;httpbin-jwt&quot;,<br>        &quot;versions&quot;: [<br>          &quot;default&quot;<br>        ]<br>      }<br>    },<br>    &quot;name&quot;: &quot;JWT Demo Policy&quot;,<br>    &quot;active&quot;: true<br>  }<br>}</pre><p>The above is a policy definition object — which defines access rights for specified APIs. In the above, we are granting access to the httpbin-jwt api. Note the policy id 5e189590801287e42a6cf5ce as we will use it later in the API definition object.</p><p>Create a new API in apps/httpbin-jwt.json as follows:</p><pre>{<br>  &quot;name&quot;: &quot;httpbin-jwt&quot;,<br>  &quot;api_id&quot;: &quot;httpbin-jwt&quot;,<br>  &quot;enable_jwt&quot;: true,<br>  &quot;jwt_signing_method&quot;: &quot;hmac&quot;,<br>  &quot;jwt_source&quot;: &quot;Zm9v&quot;,<br>  &quot;jwt_identity_base_field&quot;: &quot;sub&quot;,<br>  &quot;jwt_default_policies&quot;: [<br>    &quot;5e189590801287e42a6cf5ce&quot;<br>  ],<br>  &quot;version_data&quot;: {<br>    &quot;not_versioned&quot;: true,<br>    &quot;use_extended_paths&quot;: true,<br>    &quot;versions&quot;: {<br>      &quot;default&quot;: {<br>        &quot;name&quot;: &quot;default&quot;,<br>        &quot;global_headers&quot;: {<br>          &quot;User&quot;: &quot;$tyk_context.jwt_claims_sub&quot;<br>        }<br>      }<br>    }<br>  },<br>  &quot;proxy&quot;: {<br>    &quot;listen_path&quot;: &quot;/httpbin-jwt/&quot;,<br>    &quot;target_url&quot;: &quot;http://httpbin.org/&quot;,<br>    &quot;strip_listen_path&quot;: true<br>  },<br>  &quot;active&quot;: true,<br>  &quot;enable_context_vars&quot;: true,<br>  &quot;tag_headers&quot;: [&quot;User&quot;],<br>  &quot;strip_auth_data&quot;: true<br>}</pre><p>This api definition tells Tyk Gateway to protect the underlying service with JWT authentication. This isn’t really a lesson on how to use Tyk, but to give a few highlights.</p><p>When the gateway receives the request to /httpbin-json/, it identifies the API is protected with JWT auth, using a HMAC shared secret signing algorithm. I just set the shared secret to Zm9vwhich is the base64 encoded version of the word foo .</p><pre>echo -n foo | base64<br>Zm9v</pre><p>We identify the subject from the jwt sub claim. and Identify the default policy id to apply as 5e189590801287e42a6cf5ce the same as the policy id from policies.json.</p><p>We changed a few more core settings for the API.</p><pre>&quot;enable_context_vars&quot;: true,<br>&quot;tag_headers&quot;: [&quot;User&quot;],<br>&quot;strip_auth_data&quot;: true</pre><p>By enabling context variables, it allows us to use some templating magic to pull information out of the request context and inject it into the header or body for example.</p><p>Setting tag headers pulls information from the specified request headers and sends those values into your analytics.</p><p>Stripping auth data — is a good idea, because we don’t want the JWT to be leaked to the upstream.</p><p>Finally, we can perform a global header injection. We set the User header to the value of the JWT sub claim.</p><pre>&quot;global_headers&quot;: {<br>  &quot;User&quot;: &quot;$tyk_context.jwt_claims_sub&quot;<br>}</pre><p>Let’s restart the gateway, or hot-reload, but make sure that we mount the policies as a volume also.</p><pre>docker run -it --rm --network tyk --name tyk \<br>  -p 8080:8080 \<br>  -v $(pwd)/apps:/opt/tyk-gateway/apps \<br>  -v $(pwd)/policies/policies.json:/opt/tyk-gateway/policies/policies.json \<br>  -e TYK_GW_ENABLEANALYTICS=true \<br>  tykio/tyk-gateway:v2.9.2 tyk --conf tyk.standalone.conf</pre><pre>&lt;--- SNIPPED OUT ALL THE BORING BITS ---&gt;<br>INFO main: Detected 2 APIs<br>INFO Checking security policy: JWT api_id=httpbin-jwt api_name=httpbin-jwt<br>INFO Checking security policy: Open api_id=httpbin api_name=httpbin</pre><p>So now, we can see that our gateway has loaded 2 services, one is the original keyless or Open api. And the other service has had a JWT security policy applied.</p><p>If we now head over to <a href="https://jwt.io/">JWT.io</a> to generate our JWT — or you can use one I created earlier, and send some requests to the new API:</p><pre>curl <a href="http://localhost:8080/httpbin-jwt/get">http://localhost:8080/httpbin-jwt/get</a> \<br>  -H &#39;Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmb29AYmFyLmNvbSIsIm5hbWUiOiJBaG1ldCBTb29ybWFsbHkiLCJpYXQiOjE1MTYyMzkwMjJ9.8E-X89YnHe6m_jV4Lmyy487VnkCpzuYlsLDceCz4ScU&#39;</pre><pre>{<br>  &quot;args&quot;: {},<br>  &quot;headers&quot;: {<br>    &quot;Accept&quot;: &quot;*/*&quot;,<br>    &quot;Accept-Encoding&quot;: &quot;gzip&quot;,<br>    &quot;Host&quot;: &quot;httpbin.org&quot;,<br>    &quot;User&quot;: &quot;<a href="/service/mailto:foo@bar.com">foo@bar.com</a>&quot;,<br>    &quot;User-Agent&quot;: &quot;curl/7.67.0&quot;<br>  },<br>  &quot;origin&quot;: &quot;172.22.0.1, 151.224.16.210, 172.22.0.1&quot;,<br>  &quot;url&quot;: &quot;<a href="https://httpbin.org/get">https://httpbin.org/get</a>&quot;<br>}</pre><p>You will see that my email address foo@bar.com added to the request headers. Tyk pulled that email address out from the sub claim of the JWT. Then it striped the authorization header so it didn’t leak.</p><p>But remember, we are tagging the User header — so let’s see what it looks like in our Kibana dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HqRAuiaiGfVfeV9PYQSlRw.png" /><figcaption>Querying request context information from JWT inside Kibana</figcaption></figure><p>That’s right — we can now use the power of ElasticSearch to query &amp; filter our analytics based on our user’s email address — even though it was embedded inside a JWT!</p><p>We are not just limited to the sub claim of the JWT. If the JWT has any custom claims &amp; scopes, we can pull these out too.</p><p>We also can pull out other information from the <a href="https://tyk.io/docs/concepts/context-variables/">request context</a> including:</p><ul><li>Information from the request body</li><li>Information about the request path</li><li>IP Address</li><li>Correlation Id</li><li>Cookies</li><li>Headers</li></ul><p>Even if you are not planning on using many of the features (authentication, authorization, rate-limiting, cors support, transforms etc) that an API Gateway solution has to offer, there is a lot to be said for keeping your microservices lean and void of as much non-functional boilerplate as possible. You get a <strong>LOT</strong> of value by simply configuring the gateway as a transparent reverse proxy.</p><p>No need to immediately page or bother an engineer, no need to SSH into a production box to pull out those logs — by securing Kibana in the appropriate way, your API product manager now has the tools they need to be able to do some of those preliminary investigations and identify a problem with the client request, or identify potential problems with the underlying services.</p><p>If you wish to follow along, and get started with your first TEK stack, I’ve knocked up a quick docker-compose with some code snippets in the README of a git repo for you to get started.</p><p><a href="https://github.com/asoorm/tyk-elasticsearch-kibana">https://github.com/asoorm/tyk-elasticsearch-kibana</a></p><p>If you prefer to watch videos to follow along:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fx1tIiFBIBTY%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dx1tIiFBIBTY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fx1tIiFBIBTY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bb8adaa45683bd14d8210dc94424636/href">https://medium.com/media/4bb8adaa45683bd14d8210dc94424636/href</a></iframe><p>Have fun!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74e8fd946c39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance-tuning your Open Source Tyk API Gateway]]></title>
            <link>https://medium.com/@asoorm/performance-tuning-your-open-source-tyk-api-gateway-d48505c205a1?source=rss-6a004b640baa------2</link>
            <guid isPermaLink="false">https://medium.com/p/d48505c205a1</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[tyk]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[api-gateway]]></category>
            <dc:creator><![CDATA[Ahmet Soormally]]></dc:creator>
            <pubDate>Tue, 09 Apr 2019 07:06:30 GMT</pubDate>
            <atom:updated>2019-08-30T08:15:03.022Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kbAeV2GTCBCfLfZK.png" /></figure><p>Following the excellent twitch article mentioned in the comments, take a look at <a href="https://github.com/TykTechnologies/tyk/pull/2445">https://github.com/TykTechnologies/tyk/pull/2445</a> for implementation of a memory ballast as an alternative to tuning the go garbage collector with GOGC. Would be great to see your thoughts in the PR.</p><p>As a client-facing engineer at Tyk, I’m often asked “How fast is Tyk’s API Gateway?”. My answer is always: “damn fast — and feature packed too!”. But how do you get the optimum performance from your Tyk installation?</p><p>In this post we’ll be walking through step-by-step how you can get some insanely low latency and high throughput out of a tiny commodity server. We will get down to the nitty gritty and show you some actual numbers to help effectively tune and size your Tyk Gateway installation.</p><p>I will be showing you how to:</p><ul><li>Increase throughput from ~5000 requests per second to ~6400 requests per second</li><li>Reduce 95th %ile gateway latency by ~54% (9.2ms to 4.2ms)</li><li>Reduce CPU consumption by ~40%</li></ul><p>In order to achieve all of the above, we will be tweaking just a single environment variable: GOGC.</p><p>We will be deploying Tyk Gateway, Redis Database, Upstream Server &amp; Load Generator ALL to a single commodity 2-core DigitalOcean Droplet.</p><p>In client production deployments, we have seen Tyk Gateways performing TLS termination, Authentication, Rate-Limiting &amp; Quota checking plus analytics recording alongside Statsd instrumentation — with the Tyk Gateway introducing just 1.5ms of latency at a sustained mission critical 60k transactions per second.</p><p>This performance blog is not supposed to be scientifically accurate — if you want to do that, feel free to re-create in a more sanitised environment and let me know your results over on the <a href="https://community.tyk.io/"><strong>Tyk Community</strong></a><strong>.</strong></p><p>Does that sound like fun? Let’s get benching!</p><h3>But first, how not to deploy Tyk</h3><p>When you view showcase WordPress themes they are almost always gorilla-slow: that is, very large and with assets that are megabytes in size when the browser downloads. In real life, you will never use every single asset that the theme provides, you will likely minify and apply a few tweaks, only enabling what you need for the production site.</p><p>With this in mind, I’ve seen a couple of benchmarks of Tyk in the wild, and it is instantly clear that the deployment option chosen was a quick-start installation. While this is perfect for a few key use-cases (see next paragraph), it’s important to remember that, much like a WordPress theme, the easiest &amp; fastest way to deploy Tyk is never going to be optimally configured.</p><p>The installation I refer to is the <a href="https://github.com/TykTechnologies/tyk-pro-docker-demo"><strong>Tyk Pro Docker Demo</strong></a><strong>,</strong> which is an all-in-one installation of the professional edition of Tyk. It is great at showing off features &amp; functionality of Tyk as an enterprise API Management Platform, which can be deployed pretty much anywhere docker is available, but the amount of resource contention involved when benchmarking against this docker-compose micro-service architecture should not be surprising.</p><p>By design, Tyk is deployed as a collection of cloud-native micro-services, all working harmoniously together. Possibly the only micro-services architecture API management solution in the wild to manage your micro-services. As such, taking an out-of-the-box docker-compose to benchmark it without taking the time to understand how each component interacts with each other will almost certainly result in sub-optimal and inconsistent results.</p><h3>Sizing &amp; Configuration</h3><p>This short section will provide some insights on how to go about sizing Tyk &amp; its dependencies.</p><p>Tyk’s API Gateway is possibly the lightest and most performant solution in the industry, its only dependency being a small Redis Server.</p><p>That’s right — there is no need for MongoDB, Cassandra, Postgres or any of these heavy, computationally &amp; memory expensive databases for an Open Source installation of Tyk. In AWS, you could simply use ElastiCache, if GCP, you could use MemoryStore.</p><h3>Redis</h3><p>Redis requires enough ram to hold your tokens, temporary analytics and fast networking.</p><p>A default Redis installation will persist to disk in a non-optimal fashion, in doing so, is likely to choke the Gateway with the default configurations. For simplicity, we would recommend disabling AOF to reduce disk space usage. SAVE locks the database, and as such, BGSAVE will allow snapshotting in a non-blocking fashion.</p><p>In a real-world scenario, we recommend a Redis-cluster deployment, which will allow for linear performance improvements by sharding the data which is especially useful when you enable authentication, handle rate-limits and quotas. With Redis Cluster, you also get High Availability baked in with automatic failover. <a href="https://www.youtube.com/watch?v=ScsWSeJoq2E"><strong>Introduction to Redis Cluster</strong></a> Tyk can easily speak with a Redis Cluster, or single Redis instance.</p><p>For the purposes of this article, and to illustrate my point, we are simply deploying a single default configuration Redis master node on the same tiny Digital Ocean droplet as the gateway.</p><h3>Tyk Open Source API Gateway</h3><p>Tyk Gateway requires CPU, a small amount of RAM and fast networking. The Gateway is multi-threaded, and as such, will by default, under load, consume all the CPU made available to it by the host operating system.</p><p>We would always recommend compute optimised nodes if deploying to a cloud provider like DO, Linode, AWS, Azure or GCP. Cloud providers usually provide a good balance of RAM to CPU, and RAM should not really be a concern for Tyk to perform optimally, unless you intend to also run RAM heavy applications on the same node.</p><p>Once Tyk Gateways start consuming 60–70% CPU, we would recommend a scaling event. In the event that a node fails or is taken out for maintenance, then the remaining nodes in the cluster should have enough CPU remaining to handle the traffic from the failed node without suffering significant performance degradation.</p><h3>Installation</h3><p>We will deploy a commodity DigitalOcean server with 4GB RAM and 2 vCPUs for this benchmark. I will use a one-click-app with Docker deployed on Ubuntu 18.04 for speed of deployment.</p><p>Going against everything I have said above, I will be deploying upstream, load server, Gateway and Redis all on the same box.</p><p>This post is about how we can easily tune Tyk Gateway performance so the fact that all services are deployed on the same machine (resource contention) only proves that Tyk can go significantly faster if configured appropriately. Moving the target upstream and load generating servers to their own boxes, or ensuring appropriate resource limits if deploying inside Kubernetes for example.</p><h3>Infrastructure / Application Setup</h3><p>First, we install &amp; startup NGinX which will be our baseline upstream server — you could use any performant upstream server you like really.</p><pre># install nginx <br>apt install nginx <br>systemctl start nginx</pre><pre># Install Redis <br>apt install redis-server <br>systemctl start redis-server </pre><pre># Install Tyk Gateway <br>apt install curl gnupg apt-transport-https <br>curl -L <a href="https://packagecloud.io/tyk/tyk-gateway/gpgkey">https://packagecloud.io/tyk/tyk-gateway/gpgkey</a> | sudo apt-key add - <br>cat &gt; /etc/apt/sources.list.d/tyk_tyk-gateway.list &lt;&lt;- SOURCES deb <a href="https://packagecloud.io/tyk/tyk-gateway/ubuntu/">https://packagecloud.io/tyk/tyk-gateway/ubuntu/</a> trusty main deb-src <a href="https://packagecloud.io/tyk/tyk-gateway/ubuntu/">https://packagecloud.io/tyk/tyk-gateway/ubuntu/</a> trusty main SOURCES</pre><pre>apt update <br>apt install tyk-gateway <br>systemctl start tyk-gateway </pre><pre># check its up <br>curl -i localhost:8080/hello </pre><pre>HTTP/1.1 200 OK <br>Date: Sun, 03 Feb 2019 22:25:21 GMT <br>Content-Length: 10 <br>Content-Type: text/plain; charset=utf-8 </pre><pre>Hello Tiki</pre><h3>Gateway Proxy Configuration</h3><pre># set env var to get ip address of eth1 easily <br>export privateip=$(ifconfig eth1 | grep &quot;inet &quot; | awk &#39;{print $2}&#39;)</pre><pre># configure a keyless API to override sample application <br>cat &gt; /opt/tyk-gateway/apps/app_sample.json &lt;&lt;- EOF <br>{     <br>  &quot;name&quot;: &quot;nginx&quot;,<br>  &quot;api_id&quot;: &quot;nginx&quot;,<br>  &quot;org_id&quot;: &quot;default&quot;,<br>  &quot;definition&quot;: {<br>    &quot;location&quot;: &quot;&quot;,<br>    &quot;key&quot;: &quot;&quot;<br>  },     <br>  &quot;use_keyless&quot;: true,     <br>  &quot;auth&quot;: {         <br>    &quot;auth_header_name&quot;: &quot;&quot;     <br>  },     <br>  &quot;version_data&quot;: {         <br>    &quot;not_versioned&quot;: true,         <br>    &quot;versions&quot;: {             <br>      &quot;Default&quot;: {                 <br>        &quot;name&quot;: &quot;Default&quot;,                 <br>        &quot;expires&quot;: &quot;3000-01-02 15:04&quot;,              <br>        &quot;use_extended_paths&quot;: true,<br>        &quot;extended_paths&quot;: {<br>          &quot;ignored&quot;: [],<br>          &quot;white_list&quot;: [],<br>          &quot;black_list&quot;: []<br>        }<br>      }<br>    }<br>  },<br>  &quot;proxy&quot;: {<br>    &quot;listen_path&quot;: &quot;/nginx/&quot;,<br>    &quot;target_url&quot;: &quot;http://$privateip/&quot;,<br>    &quot;strip_listen_path&quot;: true<br>  },<br>  &quot;do_not_track&quot;: true <br>}<br>EOF </pre><pre># reload Gateway configurations via it’s control API curl -H &quot;x-tyk-authorization: 352d20ee67be67f6340b4c0605b044b7&quot; \ localhost:8080/tyk/reload/ </pre><pre># or just restart the service given that we are not in production <br>systemctl restart tyk-gateway </pre><pre># test it <br>curl -i localhost:8080/nginx/ <br>HTTP/1.1 200 OK <br>Content-Type: text/html <br>Date: Sun, 03 Feb 2019 22:38:53 GMT <br>Etag: W/&quot;5c5747c8-264&quot; <br>Last-Modified: Sun, 03 Feb 2019 19:58:00 GMT <br>Server: nginx/1.14.0 (Ubuntu) <br>X-Ratelimit-Limit: 0 <br>X-Ratelimit-Remaining: 0 <br>X-Ratelimit-Reset: 0 <br>Content-Length: 612 <br>&lt;!DOCTYPE html&gt; <br>&lt;html&gt; </pre><pre>--- SNIP ---</pre><p>As you can see, this is an out-of-the-box Tyk installation.</p><h3>Setting up benchmarking</h3><p>In order to benchmark Tyk, we will use docker-hey <a href="https://hub.docker.com/r/rcmorano/docker-hey">https://hub.docker.com/r/rcmorano/docker-hey</a></p><pre># fix firewall rules to allow docker0 access to host machine <br>iptables -A INPUT -i docker0 -j ACCEPT <br>docker pull rcmorano/docker-hey</pre><p>Baseline NginX Upstream</p><p># benchmark nginx directly to act as a baseline</p><pre>docker run --rm -it rcmorano/docker-hey -z 30s <a href="http://$privateip/">http://$privateip/</a></pre><pre>Summary:   <br>  Total: 30.0029 secs   <br>  Slowest: 0.0305 secs   <br>  Fastest: 0.0001 secs   <br>  Average: 0.0029 secs   <br>  Requests/sec: 17244.7455 </pre><pre>Response time histogram:   <br>  0.000 [1] |   <br>  0.003 [303947] |■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■   <br>  0.006 [193680] |■■■■■■■■■■■■■■■■■■■■■■■■■   <br>  0.009 [16511] |■■   <br>  0.012 [2364] |   <br>  0.015 [562] |<br>  0.018 [202] |   <br>  0.021 [38] |   <br>  0.024 [66] |   <br>  0.027 [20] |   <br>  0.031 [1] | </pre><pre>Latency distribution:   <br>  10% in 0.0007 secs   <br>  25% in 0.0016 secs  <br>  50% in 0.0027 secs  <br>  75% in 0.0040 secs <br>  90% in 0.0050 secs <br>  95% in 0.0058 secs <br>  99% in 0.0083 secs </pre><pre>---</pre><pre>Status code distribution: <br>  [200] 517392 responses</pre><p>So, out of the box, NginX performs as follows — even though docker-hey is also consuming CPU and eating system resources.</p><pre>Slowest 30.5ms, Average 2.9ms, Median 2.7ms, 95%ile 5.8ms</pre><p>So now that we have our baseline, we should see how Tyk out of the box performs as a transparent reverse proxy to NginX — even with some resource contention.</p><pre>docker run --rm -it rcmorano/docker-hey -z 30s <a href="http://$privateip:8080/nginx/">http://$privateip:8080/nginx/</a> </pre><pre>Summary: <br>  Total: 30.0035 secs <br>  Slowest: 0.0768 secs <br>  Fastest: 0.0003 secs <br>  Average: 0.0099 secs <br>  Requests/sec: 5056.8813 </pre><pre>Response time histogram: <br>  0.000 [1] | <br>  0.008 [67948] |■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ <br>  0.016 [58333] |■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ <br>  0.023 [22119] |■■■■■■■■■■■■■ <br>  0.031 [2519] |■ <br>  0.039 [544] | <br>  0.046 [198] | <br>  0.054 [33] | <br>  0.062 [18] | <br>  0.069 [6] | <br>  0.077 [5] | </pre><pre>Latency distribution: <br>  10% in 0.0034 secs <br>  25% in 0.0055 secs <br>  50% in 0.0087 secs <br>  75% in 0.0135 secs <br>  90% in 0.0177 secs <br>  95% in 0.0203 secs <br>  99% in 0.0268 secs </pre><pre>---</pre><pre>Status code distribution: <br>  [200] 151724 responses</pre><p>Not bad — Tyk is able to handle 5000 rps out of the box despite the resource contention — this tiny machine is working very hard and all the CPU is being consumed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*_QPnAGvqXgnEpi8xUmdmiA.png" /></figure><p>The problem we have here — is that our test is extremely aggressive — the average/median latency is acceptable, however there are some outliers which causes average latency to increase. The slowest request introduces 46ms latency which for me is unacceptable.</p><h3>Resource Contention</h3><p>Now in a real world scenario, you simply wouldn’t hammer the Gateway — the added latency for some of the requests is just not acceptable. Let’s throttle our rps a little.</p><p>By default, docker-hey has 50 concurrent clients. The Gateway can handle 5k rps max in this setup. So by turning down the requests per second by just 5%, let’s see how latency improves, ensuring that requests come back in a timely and consistent fashion. We will set the rate limit per consumer to 95.</p><blockquote><em>Rate limit per consumer = 5000/50 * 95% = 95</em></blockquote><pre>docker run --rm -it rcmorano/docker-hey -z 30s -q 95 <a href="http://$privateip:8080/nginx/">http://$privateip:8080/nginx/</a> </pre><pre>Summary: <br>  Total: 30.0138 secs <br>  Slowest: 0.0506 secs <br>  Fastest: 0.0002 secs <br>  Average: 0.0069 secs <br>  Requests/sec: 4713.9667 </pre><pre>Response time histogram: <br>  0.000 [1] | <br>  0.005 [58984] |■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ <br>  0.010 [57735] |■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ <br>  0.015 [18420] |■■■■■■■■■■■■ <br>  0.020 [5468] |■■■■ <br>  0.025 [740] |■ <br>  0.030 [110] | <br>  0.036 [22] | <br>  0.041 [2] | <br>  0.046 [1] | <br>  0.051 [1] | </pre><pre>Latency distribution: <br>  10% in 0.0027 secs <br>  25% in 0.0040 secs <br>  50% in 0.0060 secs <br>  75% in 0.0090 secs <br>  90% in 0.0127 secs <br>  95% in 0.0150 secs <br>  99% in 0.0192 secs </pre><pre>---</pre><pre>Status code distribution: <br>  [200] 141484 responses</pre><p>Whilst we lost just shy of 350 requests per second, look what we gained!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*X89ibRc-OZcKtYxz1xxSLQ.png" /></figure><p>Latency is now at a much more acceptable level — by not overloading the CPU. Notice how we have still not actually done any tuning, but have still managed to reduce CPU consumption by more than 10%.</p><h3>Tyk Gateway is written in Go</h3><p>Unlike various API Management solutions Tyk is written in pure Go. Go is a modern systems programming language, and is being actively developed by Google, to solve Google scale problems. Tyk does not rely on 3rd party software such as NginX to do all the heavy lifting. Go provides both Type safety, and also offers a Garbage Collector.</p><p>The Go programming language has an enviably performant concurrent, tri-colour, mark sweep garbage collector first proposed by Edsger W. Dijkstra in 1978. If you want the details, <a href="https://dl.acm.org/citation.cfm?id=359655"><strong>https://dl.acm.org/citation.cfm?id=359655</strong></a>. At a very high-level, stop-the-world GC pauses are now well below 10ms.</p><p>Despite the awesome GC, at such high throughput, compute is now being spent on scheduling the garbage collector, and collecting that garbage.</p><p>At the expense of a little extra RAM usage, we can tweak the scheduler so that it runs less often. The default value is 100%, and each time we double it, the collection frequency is halved. I’m going to set the value to 3200%. This can be achieved simply by setting a system environment variable GOGC.</p><p>It’s worth playing around with this figure for specific use-case — don’t set it too high, or you will run out of RAM and crash the VM. There will come a point where you don’t get noticeable gains. I doubled the GOGC value each test to find what the optimum figure was and that’s how I arrived at the 3200% figure.</p><h3>Tuning Tyk’s Garbage Collector</h3><pre>vi /lib/systemd/system/tyk-gateway.service </pre><pre># add this line inside the [Service] directive Environment=&quot;GOGC=3200&quot;   </pre><pre># save, quit and restart daemon and service</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/0*uEmxjEsXgM8cBCxD.jpeg" /></figure><pre>systemctl daemon-reload systemctl restart tyk-gateway</pre><p>Let’s re-run the benchmark</p><pre>docker run --rm -it rcmorano/docker-hey -z 30s -q 95 <a href="http://$privateip:8080/nginx/">http://$privateip:8080/nginx/</a> </pre><pre>Summary: <br>  Total: 30.0065 secs <br>  Slowest: 0.0425 secs <br>  Fastest: 0.0003 secs <br>  Average: 0.0048 secs <br>  Requests/sec: 4739.7088 </pre><pre>Response time histogram: <br>  0.000 [1] |  <br>  0.004 [69149] |■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ <br>  0.009 [69266] |■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ <br>  0.013 [2489] |■ <br>  0.017 [841] | <br>  0.021 [373] | <br>  0.026 [67] | <br>  0.030 [16] | <br>  0.034 [4] | <br>  0.038 [9] | <br>  0.043 [7] | </pre><pre>Latency distribution: <br>  10% in 0.0027 secs <br>  25% in 0.0035 secs <br>  50% in 0.0045 secs <br>  75% in 0.0056 secs <br>  90% in 0.0067 secs <br>  95% in 0.0077 secs <br>  99% in 0.0126 secs </pre><pre>---</pre><pre>Status code distribution: <br>  [200] 142222 responses</pre><blockquote><em>Holy Cow — we just dropped from 82% CPU usage down to less than 60%!</em></blockquote><p>Holy Cow — we just dropped from 82% CPU usage down to less than 60%! We are now using 26% less CPU than the previous test and about 40% less CPU than our first bench.</p><p>Tyk is still handling the same RPS, but rather than waste compute on collecting garbage, the Gateway is being able to proxy requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*H5scEuxwX8PDkfZAZhk0Og.png" /></figure><p>The slowest request is just 12ms slower than the slowest baseline request. Tyk is now adding sub 2ms 95%ile latency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IiZ1PkmR96CMwYLz.png" /></figure><p>At 60–70% CPU usage we would recommend adding another Tyk to the cluster. But this is a benchmarking blog — so let’s up the RPS. Let’s try full speed again to see what Tyk can handle when maxing out.</p><pre>docker run --rm -it rcmorano/docker-hey -z 30s <a href="http://$privateip:8080/nginx/">http://$privateip:8080/nginx/</a> </pre><pre>Summary: <br>  Total: 30.0050 secs <br>  Slowest: 0.0955 secs <br>  Fastest: 0.0003 secs <br>  Average: 0.0072 secs <br>  Requests/sec: 6897.5780 </pre><pre>Response time histogram: <br>  0.000 [1] | <br>  0.010 [165543] |■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ <br>  0.019 [38325] |■■■■■■■■■ <br>  0.029 [2665] |■ <br>  0.038 [332] | <br>  0.048 [75] | <br>  0.057 [6] | <br>  0.067 [8] | <br>  0.076 [2] | <br>  0.086 [3] | <br>  0.096 [2] | </pre><pre>Latency distribution: <br>  10% in 0.0030 secs <br>  25% in 0.0046 secs <br>  50% in 0.0066 secs <br>  75% in 0.0091 secs <br>  90% in 0.0120 secs <br>  95% in 0.0144 secs <br>  99% in 0.0212 secs </pre><pre>Status code distribution: <br>  [200] 205300 responses</pre><p>So the Gateway is now handling 6900 rps rather than the original 5000 rps (27% increase), and latency is still pretty good adding just 8.6ms at the 95th %ile — That’s a massive 40% improvement in latency from the out-of-the-box installation of Tyk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*i98SyW68Mz_Jown_kvcThg.png" /></figure><p>By dialling back the throughput once again by about 5% so that we are not overloading the CPUs — we set q to 131 (6900/50*0.95).</p><pre>docker run --rm -it rcmorano/docker-hey -z 30s -q 131 <a href="http://$privateip:8080/nginx/">http://$privateip:8080/nginx/</a> </pre><pre>Summary:   <br>  Total: 30.0058 secs   <br>  Slowest: 0.0473 secs   <br>  Fastest: 0.0003 secs   <br>  Average: 0.0052 secs   <br>  Requests/sec: 6412.0916 </pre><pre>Response time histogram:   <br>  0.000 [1] |   <br>  0.005 [105806] |■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■   <br>  0.010 [76053] |■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ <br>  0.014 [7891] |■■■ <br>  0.019 [1834] |■ <br>  0.024 [563] | <br>  0.028 [194] | <br>  0.033 [52] | <br>  0.038 [4] | <br>  0.043 [1] | <br>  0.047 [1] | </pre><pre>Latency distribution: <br>  10% in 0.0027 secs <br>  25% in 0.0036 secs <br>  50% in 0.0047 secs <br>  75% in 0.0060 secs <br>  90% in 0.0079 secs <br>  95% in 0.0100 secs <br>  99% in 0.0158 secs </pre><pre>---</pre><pre>Status code distribution: <br>  [200] 192400 responses</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*AyNhr5nHuhwU9tO1iTfx9w.png" /></figure><p>CPU is at a much healthier 80%, we are still handling 6400 requests per second (1400 rps more than original) and are introducing just 2.3ms average latency or 4.2ms latency at the 95th %ile. Therefore a 54% improvement on the default Tyk Installation.</p><h3>Summary</h3><p>It is important to remember that everything has been deployed on a 2-virtual-core commodity server with just 4GB of RAM.</p><p>Because we still have significant resource contention from the upstream server, load server, Redis and the Gateway all deployed on the same box, there is no way of knowing the true performance of the gateway without splitting out the components onto their own machines, or dedicating compute to each component.</p><p>Despite all of this, by tweaking a single environment variable, Tyk has been able to handle 6400 requests per second. 95% of requests come back within 10ms and subtracting NginX’s baseline latency, Tyk has introduced just 4.2ms 95th %ile latency to the request.</p><p>To top that, all the services combined are only consuming 80% CPU and less than 600Mb RAM. Further optimisations can be made to Tyk configurations to tune Tyk further in accordance with your specific use-case.</p><p>Want to give it a go? We’d love to hear your results! Drop us a line via <a href="https://community.tyk.io/"><strong>the Tyk Community</strong></a><strong> </strong>to share your own benchmarks, and help us continue to improve Tyk performance.</p><p>Happy benching!</p><p><em>Originally published at </em><a href="https://tyk.io/blog/performance-tuning-your-tyk-api-gateway/"><em>tyk.io</em></a><em> on April 9, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d48505c205a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoupling micro-services using Message-based RPC]]></title>
            <link>https://medium.com/@asoorm/decoupling-micro-services-using-message-based-rpc-fa1c12409d8f?source=rss-6a004b640baa------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa1c12409d8f</guid>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[tyk]]></category>
            <dc:creator><![CDATA[Ahmet Soormally]]></dc:creator>
            <pubDate>Mon, 06 Aug 2018 20:47:23 GMT</pubDate>
            <atom:updated>2018-08-06T20:47:23.209Z</atom:updated>
            <content:encoded><![CDATA[<p>So I was mucking around — creating a quick PoC with Tyk. I wanted to extend Tyk API Gateway so that rather than calling a typical API upstream, I would intercept the request, send to a gRPC server written in GoLang, which defers the work to an off-process messaging queue based worker. Typically — messaging queues are asynchronous — but in order to achieve a synchronous call (as far as client is concerned), we have to do a little RPC messaging queue magic. Read on if this sounds fun or just jump to the code!</p><p><a href="https://github.com/asoorm/tyk-rmq-middleware">https://github.com/asoorm/tyk-rmq-middleware</a></p><h3>What are we tinkering with?</h3><p>API Management &amp; API Gateway — Tyk is an Open Source API Gateway. The fact that I can extend Tyk by writing my own custom functionality in any language which supports gRPC is seriously powerful. <a href="https://tyk.io/">https://tyk.io</a></p><p>RabbitMQ — Many organisations use the awesome RabbitMQ <a href="https://www.rabbitmq.com/">https://www.rabbitmq.com/</a> an open-source message broker.</p><p>gRPC and protocol buffers — <a href="https://grpc.io/">https://grpc.io/</a> In gRPC a client application can directly call methods on a server application on a different machine as if it was a local object. Protocol Buffers are Google’s language-neutral mechanism for serialising structured data.</p><p>Json Schema Validation — Tyk can validate your requests against a json schema. <a href="http://json-schema.org/">http://json-schema.org/</a></p><p>GoLang — Because it’s awesome and has a Gopher as it’s mascot. <a href="https://golang.org/">https://golang.org/</a></p><p>Docker &amp; Docker-Compose — No developer toolkit is complete without docker! <a href="https://www.docker.com/">https://www.docker.com/</a></p><h3>What are we doing?</h3><p>First, we need to start all our services. We can do this easily with the following command `docker-compose up -d` This will start RabbitMQ, a Worker node &amp; a Tyk gRPC middleware server.</p><p>You can visit the rabbit management console by visiting the following url in your browser `http://localhost:15672`, and using the super secure username &amp; password guest:guest combination.</p><p>You will see that a rpc_queue has been created with a single consumer. The consumer of this queue is actually our worker service.</p><blockquote>The beauty about messaging queues, is that if you need more performance, simply start more workers. No need to faff around with Load Balancers &amp; Service Discovery et al.</blockquote><p>Our worker receives messages on the `rpc_queue`, and does something with the message, and replies to the reply_to queue with appropriate correlation_id.</p><p>We have another service, which is the `grpc-middleware` service. This is a simple gRPC server which receives messages from Tyk. When a `MyRabbitHook` is received, it reads the message body, creates a temporary queue and publishes the message to the `rpc_queue` and listens on the temporary queue for the response. Once the response has been received, it returns the response via gRPC to Tyk — which in-turn responds with the appropriate message to the client.</p><p>Once all is in place, we simply import our API definition, provided in the repo to our Tyk installation. We also need to make sure that the Tyk gateway has been started with grpc enabled alongside the location to the grpc server. Otherwise, it simply won’t work.</p><p>Testing the Json Schema Validator:</p><pre>$ curl -X POST  <a href="http://localhost:8080/httpbin/post">http://localhost:8080/httpbin/post</a> -d &#39;{&quot;firstName&quot;: &quot;Ahmet&quot;, &quot;lastName&quot;: &quot;Soormally&quot;}&#39;<br>{<br>    &quot;error&quot;: &quot;lastName: lastName is required&quot;<br>}</pre><p>Testing our gRPC Middleware which has deferred our request to some other process via RabbitMQ</p><pre>$ curl -X POST  <a href="http://localhost:8080/httpbin/post">http://localhost:8080/httpbin/post</a> -d &#39;{&quot;firstName&quot;: &quot;Ahmet&quot;, &quot;lastName&quot;: &quot;Soormally&quot;, &quot;age&quot;: 36}&#39;</pre><pre>{&quot;sentence&quot;:&quot;Ahmet Soormally is 36 year&#39;s old&quot;}</pre><h3>Caveat</h3><p>This is a quick n dirty PoC that I put together in about an hour, maybe 2 if i’m being honest.</p><p>I know of several quirks already — but am leaving them as easter eggs for you to find. If you see any issues — it’s open-source — attempt to fix, or get in touch if you need help.</p><p><a href="https://github.com/asoorm/tyk-rmq-middleware">https://github.com/asoorm/tyk-rmq-middleware</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa1c12409d8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>