<?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 Rohit Agrawal on Medium]]></title>
        <description><![CDATA[Stories by Rohit Agrawal on Medium]]></description>
        <link>https://medium.com/@agrawroh?source=rss-3de2b8464006------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yzuUrPSIVTGFob3Llcp5OQ.jpeg</url>
            <title>Stories by Rohit Agrawal on Medium</title>
            <link>https://medium.com/@agrawroh?source=rss-3de2b8464006------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 10:22:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@agrawroh/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[Preserving Identity Across Boundaries: How We Use mTLS Tunnels with Envoy]]></title>
            <link>https://agrawroh.medium.com/preserving-identity-across-boundaries-how-we-use-mtls-tunnels-with-envoy-f6df337abe54?source=rss-3de2b8464006------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6df337abe54</guid>
            <category><![CDATA[mutual-tls]]></category>
            <category><![CDATA[tunnel]]></category>
            <category><![CDATA[identity]]></category>
            <category><![CDATA[envoy-proxy]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Rohit Agrawal]]></dc:creator>
            <pubDate>Sun, 27 Apr 2025 04:44:22 GMT</pubDate>
            <atom:updated>2025-04-27T04:51:47.345Z</atom:updated>
            <content:encoded><![CDATA[<h3>Preserving Identity Across Boundaries: How We Use mTLS Tunnels with Envoy At Databricks</h3><p>In today’s distributed systems architecture, securing service-to-service communication has become mission-critical. At Databricks, like many other organizations with complex micro-service architectures, we face the challenge of protecting data as it travels across different network boundaries, particularly between our Data Plane and Control Plane.</p><p>The adoption of mutual TLS (mTLS) tunnels using Envoy Proxies has been transformative for our security posture and performance. In this post, I’ll explain what mTLS tunnels are, how they work within Envoy, and share some insights from our implementation journey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZUCYKVC8P_m4zUxE" /></figure><h3>The Challenge: Preserving Identity Across Network Boundaries</h3><blockquote>“The idea is to preserve an inner identity, associated with the original TCP stream, while client/server Envoy might have an outer TLS connection.”</blockquote><p>In modern distributed architectures, one of the most significant challenges is maintaining secure workload identity as traffic crosses network boundaries. Our specific challenge at Databricks was ensuring that Data Plane (DP) to Control Plane (CP) communication preserved the unique identity of each Data Plane while maintaining end-to-end encryption.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QXMjF7a2f-FnIOgC" /></figure><p>The fundamental challenge stems from a critical security paradigm: in HTTPS connections, client identity information is encapsulated within the encrypted TLS session. For our architecture, which needed to handle both trusted first-party clients and untrusted third-party clients, this created a complex problem. We required a bulletproof mechanism to authenticate the Data Plane’s identity before permitting any communication with Control Plane services. Simply terminating TLS connections at the network edge would compromise our end-to-end encryption security model. Additionally, we couldn’t modify the client applications themselves, especially for third-party clients outside our control, meaning the solution had to be transparent to the communicating endpoints while still enforcing strong identity validation.</p><p>We needed a solution that would:</p><ol><li><strong>Preserve workload identity</strong>: Each Data Plane has its own unique identity that must be verifiable by the Control Plane.</li><li><strong>Enforce strict boundary controls</strong>: Prevent scenarios which could lead to potential data exfiltration.</li><li><strong>Maintain end-to-end encryption</strong>: Keep client connections secure throughout their journey.</li><li><strong>Work with both first-party and third-party clients</strong>: Support all types of clients without requiring modifications to their code.</li></ol><p>Standard TLS solutions fell short because, as one GitHub issue discussing Envoy put it, <em>“The idea is to preserve an inner identity, associated with the original TCP stream, while client/server Envoy might have an outer TLS connection.”</em> . This captures precisely what we needed to achieve.</p><p>The traditional approach of terminating TLS at the edge and re-encrypting with new certificates would have broken our zero-trust security model. We couldn’t rely on network identity (like IP addresses) since “IP addresses in Kubernetes are scoped to a cluster, and the moment you cross a cluster boundary, you have to come up with another mechanism for identity.”</p><p>This is where mTLS tunneling helped, allowing us to wrap the original encrypted traffic in another authentication layer that preserved identity information across network boundaries.</p><h3>Understanding mTLS Tunnels</h3><p>Before diving into our implementation, let’s understand what mTLS tunneling is and why it matters.</p><h4>What is an mTLS Tunnel?</h4><p>A TCP tunnel essentially encapsulates TCP traffic within another network protocol (in our case, HTTP/2). When we add mutual TLS (mTLS) to this equation, we create a secure channel where:</p><ol><li>Both parties authenticate each other with certificates</li><li>All data is encrypted in transit</li><li>The connection is resistant to man-in-the-middle attacks</li><li>The tunnel can traverse network boundaries that might otherwise block direct connections</li></ol><p>The key distinction from regular TLS is the “mutual” aspect. Both sides verify each other’s identity, not just the client verifying the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwnVffvTDXn7QLxWxpcDLA.png" /><figcaption>E2E Request from the client to the server</figcaption></figure><h3>The Envoy Implementation</h3><p>Envoy is capable of tunneling TCP traffic over HTTP/2. Here’s how we structure our tunnels:</p><pre>Client → (TCP) → Client-side Envoy → (HTTP/2 POST with mTLS) → Server-side Envoy → (TCP) → Server</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Oe-dNjtiNXQ-0zdN" /></figure><p>The process involves several steps:</p><ol><li><strong>Encapsulation</strong>: Client-side Envoy wraps the original TCP traffic in HTTP/2 POST request</li><li><strong>Authentication</strong>: Both Envoy proxies authenticate each other using certificates</li><li><strong>Secure Transmission</strong>: The encapsulated data travels securely through the tunnel</li><li><strong>Decapsulation</strong>: Server-side Envoy unwraps the traffic and forwards it to the actual destination</li></ol><h4>Support for Various Protocols</h4><p>A key advantage of this approach is its protocol flexibility. While HTTPS traffic is commonly protected this way, our implementation also handles other TCP-based protocols like SQL, etc.</p><h4>SQL and PostgreSQL Traffic</h4><p>For database communications, we can tunnel SQL and PostgreSQL traffic through the same secure channels. This allows unified security controls for diverse traffic types without protocol-specific security implementations.</p><h4>HTTP/3 Considerations</h4><p>HTTP/3 brings significant performance benefits including reduced latency (0-RTT connection with TLS 1.3) and improved performance through stream multiplexing, header compression, and better flow control. Envoy v1.22 has made QUIC generally available for <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/http/http3#http-3-downstream">downstream connections</a>. <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/http/http3#http-3-upstream">Client HTTP/3 support</a> is in Alpha but could be used if both the client as well as the server Envoy are getting deployed in a controlled environment.</p><p>It’s important to distinguish between tunneling HTTP/3 and tunneling over HTTP/3:</p><ol><li><strong>Tunneling HTTP/3</strong>: Encapsulating HTTP/3 (UDP-based) traffic within another protocol.</li><li><strong>Tunneling over HTTP/3</strong>: Using HTTP/3 as the encapsulation protocol.</li></ol><p>Since HTTP/3 operates over UDP rather than TCP, tunneling HTTP/3 requires UDP Proxy on the client-side, and the server must be configured to properly decapsulate UDP traffic. There is support in Envoy to do this but we’ll mainly focus on TCP in this article.</p><h3>Our Implementation at Databricks</h3><p>At Databricks, we use mTLS tunnels to secure communication between our Data Plane (DP) and Control Plane (CP). Let me walk through our specific setup.</p><h4>Architecture Overview</h4><p>We deploy Envoy at multiple layers , as our main ingress proxy and as an egress filtering proxy. Here’s how a typical request flows:</p><ul><li>Client makes an HTTPS request to our Control Plane.</li><li>IP Table rules redirect this traffic to Data Plane Envoy Proxy.</li><li>Data PlaneEnvoy Proxy starts an mTLS tunnel with the Control Plane Envoy Proxy.</li><li>The original request travels through this tunnel.</li><li>Control Plane Envoy terminates both the outer mTLS and inner TLS connection with the Data Plane client.</li><li>The request gets forwarded to its final destination service.</li></ul><h4>Double TLS Termination</h4><p>A key aspect of our implementation is the double TLS termination strategy:</p><ol><li><strong>Outer mTLS Connection</strong>: Between Data Plane Envoy and Control Plane Envoy using certificates which are bound to the Data Planes. Each Data Plane gets a unique identity and these certs are rotated periodically.</li><li><strong>Inner TLS Connection</strong>: Between the client and the ingress service. In our case ingress mounts the domain certificates and the inner link is just TLS.</li></ol><p>This approach allows us to maintain end-to-end security while still enabling inspection at the boundary when necessary.</p><h4>Certificate Management</h4><p>For the mTLS tunnels to work properly, certificate management is a crucial part. Our certificates:</p><ul><li>Are Data Plane specific and provides granular access control.</li><li>Get managed by a special Secrets Manager service which is responsible for distributing them to the Data Planes and also rotating them periodically.</li><li>Uses an in-house CA as the trusted authority.</li><li>Include unique Data Plane identity for additional validation on the Control Plane side.</li></ul><p>Let’s take a look at the Envoy configs,</p><h4>Downstream Envoy</h4><pre># Testing: curl -vvv --resolve google.com:443:127.0.0.1 https://google.com/<br>admin:<br>  address:<br>    socket_address:<br>      protocol: TCP<br>      address: 127.0.0.1<br>      port_value: 9901<br>static_resources:<br>  listeners:<br>  - name: main_listener<br>    address:<br>      socket_address:<br>        protocol: TCP<br>        address: 127.0.0.1<br>        port_value: 443<br>    listener_filters:<br>    - name: envoy.filters.listener.tls_inspector<br>      typed_config:<br>        &quot;@type&quot;: type.googleapis.com/envoy.extensions.filters.listener.tls_inspector.v3.TlsInspector<br>    filter_chains:<br>    - filters:<br>      - name: tcp<br>        typed_config:<br>          &quot;@type&quot;: type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy<br>          stat_prefix: tcp_stats<br>          cluster: databricks_upstream<br>          tunneling_config:<br>            hostname: me.storage.staging.azuredatabricks.net<br>            use_post: true<br>            post_path: &quot;/dp-cp-tls-tunnel&quot;<br>            headers_to_add:<br>            - header:<br>                key: &quot;x-databricks-tunnel-traffic&quot;<br>                value: &quot;true&quot;<br>              append_action: &quot;OVERWRITE_IF_EXISTS_OR_ADD&quot;<br>              keep_empty_value: false<br>  clusters:<br>  - name: databricks_upstream<br>    type: LOGICAL_DNS<br>    dns_lookup_family: V4_ONLY<br>    lb_policy: ROUND_ROBIN<br>    connect_timeout: 5s<br>    typed_extension_protocol_options:<br>      envoy.extensions.upstreams.http.v3.HttpProtocolOptions:<br>        &quot;@type&quot;: type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions<br>        explicit_http_config:<br>          http3_protocol_options: {}<br>    transport_socket:<br>      name: envoy.transport_sockets.quic<br>      typed_config:<br>        &quot;@type&quot;: type.googleapis.com/envoy.extensions.transport_sockets.quic.v3.QuicUpstreamTransport<br>        upstream_tls_context:<br>          sni: databricks.com<br>    load_assignment:<br>      cluster_name: databricks_upstream<br>      endpoints:<br>      - lb_endpoints:<br>        - endpoint:<br>            address:<br>              socket_address:<br>                address: 127.0.0.1<br>                port_value: 9102</pre><h4>Upstream Envoy</h4><pre># This configuration terminates a POST request and sends the POST payload upstream.<br># It can be used to test TCP tunneling as described in<br># https://envoyproxy.io/docs/envoy/latest/intro/arch_overview/http/upgrades<br>admin:<br>  address:<br>    socket_address:<br>      protocol: TCP<br>      address: 127.0.0.1<br>      port_value: 9902<br>bootstrap_extensions:<br>  - name: envoy.bootstrap.internal_listener<br>    typed_config:<br>      &quot;@type&quot;: type.googleapis.com/envoy.extensions.bootstrap.internal_listener.v3.InternalListener<br>static_resources:<br>  listeners:<br>  - name: internal_listener<br>    internal_listener: {}<br>    listener_filters:<br>    - name: envoy.filters.listener.tls_inspector<br>      typed_config:<br>        &quot;@type&quot;: type.googleapis.com/envoy.extensions.filters.listener.tls_inspector.v3.TlsInspector<br>    filter_chain_matcher:<br>      matcher_list:<br>        matchers:<br>        - predicate:<br>            single_predicate:<br>              input:<br>                name: envoy.matching.inputs.transport_protocol<br>                typed_config:<br>                  &quot;@type&quot;: type.googleapis.com/envoy.extensions.matching.common_inputs.network.v3.TransportProtocolInput<br>              value_match:<br>                exact: tls<br>          on_match:<br>            action:<br>              name: pick-https-traffic-chain<br>              typed_config:<br>                &quot;@type&quot;: type.googleapis.com/google.protobuf.StringValue<br>                value: https-traffic<br>      on_no_match:<br>        action:<br>          name: pick-http-traffic-chain<br>          typed_config:<br>            &quot;@type&quot;: type.googleapis.com/google.protobuf.StringValue<br>            value: http-traffic<br>    filter_chains:<br>      - name: http-traffic<br>        filters:<br>        - name: tcp_proxy<br>          typed_config:<br>            &quot;@type&quot;: type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy<br>            stat_prefix: https<br>            cluster: google<br>      - name: https-traffic<br>        filters:<br>        - name: tcp_proxy<br>          typed_config:<br>            &quot;@type&quot;: type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy<br>            stat_prefix: https<br>            cluster: databricks<br>            access_log:<br>            - name: envoy.file_access_log<br>              typed_config:<br>                &quot;@type&quot;: type.googleapis.com/envoy.extensions.access_loggers.file.v3.FileAccessLog<br>                path: &quot;access_upstream.logs&quot;<br>                log_format:<br>                  text_format_source:<br>                    inline_string: &quot;%FILTER_STATE(envoy.string:PLAIN)%\n&quot;<br>  - name: main_listener<br>    address:<br>      socket_address:<br>        protocol: UDP<br>        address: 127.0.0.1<br>        port_value: 9102<br>    udp_listener_config:<br>      quic_options: {}<br>      downstream_socket_config:<br>        prefer_gro: true<br>    filter_chains:<br>      - name: allow-traffic<br>        filters:<br>        - name: envoy.filters.network.http_connection_manager<br>          typed_config:<br>            &quot;@type&quot;: type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager<br>            codec_type: HTTP3<br>            stat_prefix: ingress_http<br>            forward_client_cert_details: SANITIZE_SET<br>            set_current_client_cert_details:<br>              cert: true<br>            route_config:<br>              name: main_route<br>              virtual_hosts:<br>              - name: main_vh<br>                domains:<br>                - &quot;*&quot;<br>                routes:<br>                - match:<br>                    path: &quot;/dp-cp-tls-tunnel&quot;<br>                    headers:<br>                    - name: &quot;:method&quot;<br>                      string_match:<br>                        exact: &quot;POST&quot;<br>                    - name: &quot;x-databricks-tunnel-traffic&quot;<br>                      present_match: true<br>                  route:<br>                    cluster: traffic_handler<br>                    upgrade_configs:<br>                    - upgrade_type: CONNECT<br>                      connect_config:<br>                        allow_post: true<br>            http_filters:<br>            - name: envoy.filters.http.rbac<br>              typed_config:<br>                &quot;@type&quot;: type.googleapis.com/envoy.extensions.filters.http.rbac.v3.RBAC<br>                matcher:<br>                  matcher_list:<br>                    matchers:<br>                    - on_match:<br>                        action:<br>                          name: envoy.filters.rbac.action<br>                          typed_config:<br>                            &quot;@type&quot;: type.googleapis.com/envoy.config.rbac.v3.Action<br>                            action: ALLOW<br>                            name: sni-host-matching-allow-request<br>                      predicate:<br>                        or_matcher:<br>                          predicate:<br>                          - single_predicate:<br>                              input:<br>                                name: sni<br>                                typed_config:<br>                                  &quot;@type&quot;: type.googleapis.com/envoy.extensions.matching.common_inputs.network.v3.ServerNameInput<br>                              value_match:<br>                                custom:<br>                                  name: envoy.string_matcher.lua<br>                                  typed_config:<br>                                    &quot;@type&quot;: type.googleapis.com/envoy.extensions.string_matcher.lua.v3.Lua<br>                                    source_code:<br>                                      inline_string: &quot;function envoy_match(sni)\n  return sni == nil or sni == &#39;&#39;\nend\n&quot;<br>                          - single_predicate:<br>                              custom_match:<br>                                name: sni-matcher<br>                                typed_config:<br>                                  &quot;@type&quot;: type.googleapis.com/xds.type.matcher.v3.CelMatcher<br>                                  expr_match:<br>                                    parsed_expr:<br>                                      expr:<br>                                        call_expr:<br>                                          args:<br>                                          - id: 2<br>                                            select_expr:<br>                                              field: host<br>                                              operand:<br>                                                id: 1<br>                                                ident_expr:<br>                                                  name: request<br>                                          - id: 5<br>                                            select_expr:<br>                                              field: requested_server_name<br>                                              operand:<br>                                                id: 4<br>                                                ident_expr:<br>                                                  name: connection<br>                                          function: _==_<br>                                        id: 3<br>                              input:<br>                                name: envoy.matching.inputs.cel_data_input<br>                                typed_config:<br>                                  &quot;@type&quot;: type.googleapis.com/xds.type.matcher.v3.HttpAttributesCelMatchInput<br>                  on_no_match:<br>                    action:<br>                      name: action<br>                      typed_config:<br>                        &quot;@type&quot;: type.googleapis.com/envoy.config.rbac.v3.Action<br>                        action: DENY<br>                        name: deny-request<br>            - name: header-to-filter-state<br>              typed_config:<br>                &quot;@type&quot;: type.googleapis.com/envoy.extensions.filters.http.set_filter_state.v3.Config<br>                on_request_headers:<br>                - object_key: envoy.string<br>                  format_string:<br>                    text_format_source:<br>                      inline_string: &quot;%REQ(x-forwarded-client-cert)%&quot;<br>                  shared_with_upstream: ONCE<br>            - name: envoy.filters.http.router<br>              typed_config:<br>                &quot;@type&quot;: type.googleapis.com/envoy.extensions.filters.http.router.v3.Router<br>            http2_protocol_options:<br>              allow_connect: true<br>            upgrade_configs:<br>            - upgrade_type: CONNECT<br>        transport_socket:<br>          name: tls<br>          typed_config:<br>            &quot;@type&quot;: type.googleapis.com/envoy.extensions.transport_sockets.quic.v3.QuicDownstreamTransport<br>            downstream_tls_context:<br>              common_tls_context:<br>                alpn_protocols: &quot;h3&quot;<br>                validation_context:<br>                  trust_chain_verification: ACCEPT_UNTRUSTED<br>                  trusted_ca:<br>                    filename: /opt/homebrew/etc/ca-certificates/cert.pem<br>                tls_certificates:<br>                - certificate_chain:<br>                    filename: &quot;server.crt&quot;<br>                  private_key:<br>                    filename: &quot;server.key&quot;<br>  clusters:<br>  - name: traffic_handler<br>    transport_socket:<br>      name: envoy.transport_sockets.internal_upstream<br>      typed_config:<br>        &quot;@type&quot;: type.googleapis.com/envoy.extensions.transport_sockets.internal_upstream.v3.InternalUpstreamTransport<br>        passthrough_metadata:<br>        - name: cluster_metadata<br>          kind:<br>            cluster: {}<br>        transport_socket:<br>          name: envoy.transport_sockets.raw_buffer<br>          typed_config:<br>            &quot;@type&quot;: type.googleapis.com/envoy.extensions.transport_sockets.raw_buffer.v3.RawBuffer<br>    load_assignment:<br>      cluster_name: traffic_handler<br>      endpoints:<br>      - lb_endpoints:<br>        - endpoint:<br>            address:<br>              envoy_internal_address:<br>                server_listener_name: internal_listener<br>  - name: databricks<br>    connect_timeout: 5s<br>    type: LOGICAL_DNS<br>    dns_lookup_family: V4_ONLY<br>    lb_policy: ROUND_ROBIN<br>    load_assignment:<br>      cluster_name: databricks<br>      endpoints:<br>      - lb_endpoints:<br>        - endpoint:<br>            address:<br>              socket_address:<br>                address: www.databricks.com<br>                port_value: 443</pre><h3>The Real-World Benefits of mTLS Tunneling</h3><p>Implementing mTLS tunnels with Envoy transformed our approach to secure service communication at Databricks. Beyond the technical elegance of the solution, the practical benefits were immediate and significant:</p><h4>Enhanced Security Through Identity</h4><p>The most valuable outcome was achieving true zero-trust security across network boundaries. Every Data Plane now communicates with the Control Plane using its unique, verifiable identity. This eliminated the security gaps that previously existed when traffic crossed network perimeters, creating a consistent security model regardless of where services are deployed.</p><h4>Seamless Client Experience</h4><p>For developers and third-party clients interfacing with our services, the security improvements are completely transparent. They continue using standard HTTPS connections without modification, while behind the scenes, their traffic is wrapped in a secure identity layer that preserves their original encrypted session all the way to its destination.</p><h4>Universal Protocol Support</h4><p>One surprising advantage emerged in our ability to secure non-HTTP protocols through the same tunneling approach. SQL and PostgreSQL traffic now traverses the same secure tunnels as HTTP requests, bringing uniform security to diverse communication protocols without specialized implementations for each one.</p><h4>Simplified Operations</h4><p>Centralizing security at key architectural boundaries has dramatically simplified operations for us. Rather than managing security at dozens of individual service endpoints, we now enforce security policies at a smaller number of well-defined boundaries, making monitoring and compliance verification more straightforward.</p><h3>Overcoming Implementation Challenges</h3><p>While the benefits were substantial, implementing mTLS tunneling across our infrastructure presented several obstacles we had to overcome. Here’s how we addressed them:</p><h4>Challenge #1: Debugging Encrypted Traffic</h4><p><strong>Problem:</strong> Once traffic was tunneled and encrypted twice, traditional debugging became nearly impossible.</p><p><strong>Solution:</strong> We created a multi-layer observability approach:</p><ol><li><strong>Data Plane Visibility</strong>: Data Plane Envoy now emits specialized logs from the TCP listener dedicated to tunneling.</li><li><strong>Control Plane Visibility</strong>: Control Plane Envoy generates detailed logs from both outer and inner listeners.</li><li><strong>Correlation IDs</strong>: We implemented unique request identifiers that persist across both tunnel layers.</li></ol><p>These changes allow our team to trace requests through every stage of the tunneling process without compromising encryption.</p><h4>Challenge #2: Certificate Lifecycle Management</h4><p><strong>Problem:</strong> Certificate expiration could instantly break cross-plane communication.</p><p><strong>Solution:</strong> We built a robust certificate management system that:</p><ul><li>Automatically rotates certificates before expiration.</li><li>Maintains a grace period where both old and new certificates are valid.</li><li>Monitors certificate health with proactive alerts.</li><li>Distributes certificates securely to Data Planes through a dedicated Secrets Manager service.</li></ul><h3>Best Practices From Our Journey</h3><p>Our implementation experience yielded valuable lessons that can benefit any organization considering mTLS tunneling:</p><h4>1. Map Your Trust Boundaries First</h4><p>Before writing a single line of configuration, invest time in clearly mapping where your network boundaries exist and which identities should be trusted at each boundary. This clarity will guide your entire implementation.</p><h4>2. Design for Debugging From Day One</h4><p>Build observability into your tunneling architecture from the start. Each component should emit logs that include correlation IDs to trace requests across boundaries, and metrics should track tunnel health indicators like certificate expiration times and connection failures.</p><h4>3. Implement Gradual Rollout Strategies</h4><p>We rolled out tunneling incrementally, starting with non-critical services and gradually expanding to more sensitive workloads. This approach allowed us to refine our implementation and debug issues without risking critical production traffic.</p><h4>4. Embed Identity in Infrastructure</h4><p>Rather than treating identity as an application concern, build it into your infrastructure layer. In our case, embedding workspace identifiers directly in certificates proved more reliable than depending on application headers or tokens.</p><h4>5. Embrace Automation</h4><p>Certificate management and tunnel configuration are too critical to leave to manual processes. Invest in automation for certificate rotation, configuration deployment, and health monitoring to prevent human error from causing outages.</p><h3>Looking Forward: The Future of Service Mesh Security</h3><p>While our current implementation has been transformative, we’re already working on several enhancements that point to the future of service communication security:</p><h4>Dynamic Traffic Controls</h4><p>We’re developing systems that automatically adjust tunneling configurations based on observed traffic patterns, security events, and infrastructure health. This self-tuning approach will optimize both security and performance without manual intervention.</p><h4>Enhanced Contextual Authentication</h4><p>Future versions of our system will incorporate additional context signals beyond certificates, such as request patterns, client behavior profiles, and time-of-day factors, to make more sophisticated authentication decisions.</p><h4>Cross-Cloud Federated Identity</h4><p>As we expand to multi-cloud environments, we’re extending our tunneling approach to support federated identities across different cloud providers, maintaining consistent security controls regardless of where workloads run.</p><h3>Conclusion: Security Without Compromise</h3><p>Implementing mTLS tunnels using Envoy has fundamentally transformed how we approach service-to-service communication at Databricks. We’ve achieved what once seemed impossible: strong identity-based security across network boundaries without sacrificing developer experience or performance.</p><p>The approach described in this post isn’t just a technical implementation, it represents a security philosophy where identity, not network location, forms the foundation of access decisions. As service architectures become increasingly distributed across multiple clouds and environments, this identity-centric approach will only become more essential.</p><p>If you’re considering a similar implementation, start small, focus on your most critical boundaries first, and build robust observability from the beginning. The effort invested will pay dividends in both security posture and operational simplicity.</p><p><em>Would you like to learn more about our approach to secure service communication? Share your questions and experiences in the comments below, or reach out to our team directly.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6df337abe54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Kubernetes Load Balancing: Why You Need Endpoint Discovery]]></title>
            <link>https://agrawroh.medium.com/beyond-kubernetes-load-balancing-why-you-need-endpoint-discovery-cfa8ee6eaa48?source=rss-3de2b8464006------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfa8ee6eaa48</guid>
            <category><![CDATA[service-mesh]]></category>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[envoy-proxy]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[load-balancing]]></category>
            <dc:creator><![CDATA[Rohit Agrawal]]></dc:creator>
            <pubDate>Tue, 31 Dec 2024 18:32:35 GMT</pubDate>
            <atom:updated>2025-01-04T16:29:36.033Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t-mEJOYnzbU79zO0bXGDtQ.png" /><figcaption>Efficiently scale your Kubernetes workloads</figcaption></figure><p>When running a distributed system at scale, load balancing becomes critical to system performance, reliability, and cost efficiency. At Databricks, as our platform grew to serve millions of notebooks, jobs, and ML models, we discovered that Kubernetes’ default load balancing mechanisms weren’t enough to handle our complex workload patterns.</p><p>In this story we’ll share how we tackled these challenges to improve the availability of our system and also reduced the overall cloud costs.</p><h3>The Problem with Kubernetes Load Balancing</h3><p>Kubernetes, by default, uses a simple random load balancing strategy through kube-proxy’s iptables mode. While this works well for simple applications, it presents several challenges for complex, high-scale systems:</p><h4>1. Not All Requests Are Created Equal</h4><p>In a typical data platform like Databricks, different requests can have vastly different resource requirements. Some API calls might be quick metadata operations, while others could involve heavy computation or data movement. Random load balancing doesn’t account for these differences, leading to uneven resource utilization across pods.</p><h4>2. Connection Reuse Creates Hotspots</h4><p>Modern systems often use connection pooling and keep-alive connections to improve performance. However, this can create an unexpected side effect: once a connection is established, it stays with that same backend pod until the connection is closed. During deployments or scale events, this means traffic doesn’t shift quickly enough to new pods when we are rolling our a new version, creating potential bottlenecks.</p><h4>3. Streaming Workloads Create Imbalance</h4><p>gRPC Bi-Di streams and WebSocket connections, which are common in interactive computing platforms, can stick to specific endpoints for extended periods. With random load balancing, these long-lived connections might concentrate on a few pods, leading to overload while other pods remain underutilized.</p><h4>4. No Built-in Failover</h4><p>Perhaps most critically, when a pod becomes unhealthy, kube-proxy doesn’t automatically failover to healthy pods. This forces clients to implement their own retry logic, which can be inefficient and potentially overwhelming during partial outages.</p><h3>The Cost of Suboptimal Load Balancing</h3><p>At Databricks, these issues weren’t just theoretical. We found ourselves significantly over-provisioning resources to handle the uneven load distribution. Our analysis showed that optimizing load balancing could potentially save up to <strong>$75,000 per month</strong> per-region in cloud costs.</p><h3>Enter EDS: A Smart Load Balancing Solution</h3><p>In September 2022, we began developing the Endpoint Discovery Service (EDS) based on the open-source java-control-plane implementation. The design goals were clear:</p><ul><li>Make load balancing load-aware and dynamic.</li><li>Ensure backward compatibility.</li><li>Maintain high availability with failover capabilities.</li><li>Keep it simple for service teams to adopt.</li></ul><p>EDS works by:</p><ol><li><strong>Dynamic Load Awareness</strong>: EDS continuously monitors system metrics from each pod, initially using M3 metrics and later moving to direct metric collection for reduced latency.</li><li><strong>Intelligent Weight Calculation</strong>: Instead of random distribution, EDS calculates weights for each endpoint based on their current load and capacity, ensuring requests are directed to the least loaded pods. The weight calculation formula considers multiple factors: `weight = 100 * (1 — load_1m / nr_cpus) / Σ(1 — load_1m(i) / nr_cpus(i))`</li><li><strong>Fast Failover</strong>: When pods become unhealthy, EDS quickly removes them from the load balancing pool and redistributes traffic to healthy instances, even across availability zones if necessary.</li><li><strong>Safe Rollout Mechanisms</strong>: EDS supports various rollout strategies, including traffic splitting, where services can designate a percentage of traffic to use EDS load balancing while keeping the rest on the traditional method.</li></ol><h3>Implementation Details</h3><p>One key design decision was implementing EDS as a soft dependency. We configured API Proxy to use an aggregate cluster setup:</p><ul><li><strong>Primary:</strong> EDS-derived cluster with weighted least request load balancing</li><li><strong>Secondary:</strong> Traditional ClusterIP-based cluster as fallback</li></ul><p>This design ensures that if EDS becomes unavailable, traffic automatically falls back to the traditional Kubernetes load balancing without service disruption. We also implemented a “Big Red Button” via our Global Operations Console (GOC) to instantly disable EDS for any service if needed.</p><h3>Results in Production</h3><p>After rolling out EDS across our platform in waves (starting with dev environments and gradually moving to production), we observed:</p><ul><li><strong>Better Load Distribution</strong>: CPU utilization variance across pods decreased significantly, with the difference between most and least loaded pods dropping from 3x to 1.2x</li><li><strong>Faster Recovery</strong>: During pod failures, traffic redistribution time improved from seconds to milliseconds</li><li><strong>Resource Efficiency</strong>: We were able to reduce our pod count by up to 50% while maintaining the same performance SLAs</li><li><strong>Improved Rollouts</strong>: New pods during scale-up events now receive their fair share of traffic immediately</li></ul><h3>Industry Context and Future</h3><p>Our journey with EDS mirrors similar challenges faced by other large-scale platforms. Google’s Maglev load balancer and Amazon’s Application Load Balancer both implement sophisticated load-aware balancing strategies. However, these solutions are typically not available to companies running their own Kubernetes clusters.</p><p>Looking forward, we’re continuing to enhance EDS with:</p><ul><li>Integration with our RPC clients for service-to-service communication.</li><li>Support for custom metrics and weighting algorithms.</li><li>Enhanced observability and debugging capabilities.</li><li>Potential integration with Cluster Discovery Service (CDS) for more dynamic configuration.</li></ul><p>The journey from Kubernetes’ basic load balancing to EDS shows how solving fundamental infrastructure challenges can have far-reaching impacts on system reliability, performance, and cost efficiency. Today, all our workloads at Databricks use EDS, and we’ve built it into our RPC clients natively so that not only our API Gateway (powered by Envoy) but all other clients are also using the same system.</p><p>Remember, while Kubernetes provides a great foundation for container orchestration, as your system grows, you might need to build additional layers to handle your specific scaling challenges. EDS is just one example of how we at Databricks have extended the Kubernetes ecosystem to better serve our needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfa8ee6eaa48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Envoy’s CEL Filters: Advanced Access Log Control]]></title>
            <link>https://agrawroh.medium.com/mastering-envoys-cel-filters-advanced-access-log-control-50809f4c66cd?source=rss-3de2b8464006------2</link>
            <guid isPermaLink="false">https://medium.com/p/50809f4c66cd</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[service-mesh]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[extensibility]]></category>
            <category><![CDATA[envoy-proxy]]></category>
            <dc:creator><![CDATA[Rohit Agrawal]]></dc:creator>
            <pubDate>Sun, 22 Dec 2024 16:30:44 GMT</pubDate>
            <atom:updated>2024-12-24T15:00:59.902Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sj0GvYClFGmNj9-q4a35fg.png" /><figcaption>When regular filters just aren’t enough… there’s always CEL!</figcaption></figure><p>In our <a href="https://medium.com/@agrawroh/scaling-envoy-proxy-how-we-slashed-logging-costs-by-65-e73d922dea26">previous post</a> about Envoy logging optimization, we explored basic filtering techniques to reduce logging volume and improve proxy performance.</p><p>But what happens when these basic filters aren’t enough? What if you need to filter based on backend latency? Or create complex conditions combining multiple headers and response codes?</p><p>This is where <a href="https://cel.dev/">CEL (Common Expression Language)</a> shines. It’s a powerful tool for crafting sophisticated rules.</p><h4>What is CEL?</h4><blockquote>“CEL makes it easy to write sophisticated access log filtering rules while maintaining performance”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*py58MwioujnDgHdSxNoNhA.png" /></figure><p>The <a href="https://github.com/google/cel-spec">Common Expression Language (CEL)</a> isn’t just another filtering mechanism — it’s a game-changer for Envoy configurations. Here’s why it matters:</p><ol><li><strong>Speed:</strong> Designed for linear-time execution.</li><li><strong>Extensibility:</strong> Built to be embedded in applications.</li><li><strong>Developer-Friendly:</strong> Familiar syntax for anyone who knows C++/Java/JavaScript</li></ol><h4>The Power of Expressive Filtering</h4><blockquote>“CEL simplifies what would otherwise require multiple nested filters in Envoy’s native configuration”</blockquote><p>Before diving into examples, here’s what you can access with CEL expressions:</p><ol><li><strong>Request Data:</strong> Path, headers, method, size, duration, protocol</li><li><strong>Response Data:</strong> Status codes, latency, size, headers, gRPC status</li><li><strong>Connection Details:</strong> TLS info, addresses, ports, certificates</li><li><strong>Upstream Info:</strong> Connection details, latency, attempt counts<br>Metadata: Dynamic request metadata, filter states</li></ol><p><em>See the complete list of available attributes in the </em><a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/advanced/attributes#arch-overview-attributes"><em>Envoy documentation</em></a><em>.</em></p><p>Now, let’s look at some real-world examples that showcase CEL’s capabilities:</p><pre>// Catch slow error responses<br>response.backend_latency &gt;= duration(&quot;2s&quot;) &amp;&amp; response.code &gt;= 500<br><br>// Monitor large API responses<br>response.size &gt;= 1048576 &amp;&amp; request.path.startsWith(&quot;/api/v2&quot;)<br><br>// Track specific error conditions<br>request.headers[&quot;x-custom-header&quot;] == &quot;special-value&quot; &amp;&amp; <br>    (response.code == 429 || response.grpc_status == 14)</pre><h4>Implementing CEL in Practice</h4><p>With CEL, you can craft rules for critical use-cases like performance monitoring (tracking backend latency), security auditing (logging suspicious TLS patterns), debugging (capturing retry attempts), and traffic analysis (monitoring API versions and payload sizes).</p><p>Let’s see how you can use CEL to implement a logging filter in your Envoy configuration.</p><p>Before we dive in, it’s worth noting that CEL is part of an <a href="https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/accesslog/v3/accesslog.proto#envoy-v3-api-field-config-accesslog-v3-accesslogfilter-extension-filter">Extension Filter</a>. Envoy provides some built-in filters and also allows you to create your own <a href="https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/accesslog/filters/filters">pluggable extensions</a> to customize access log filtering. We’ll discuss how to build your own filters in an upcoming post. For now, just remember that CEL (<a href="https://www.envoyproxy.io/docs/envoy/latest/api-v3/extensions/access_loggers/filters/cel/v3/cel.proto">Expression Filter</a>) is one of these extensions and comes bundled with Envoy.</p><p>Here’s a configuration that logs requests only when the backend response time exceeds 2 seconds:</p><pre>access_log:<br>- name: envoy.access_loggers.file<br>  filter:<br>    extension_filter:<br>      name: envoy.filters.accesslog.cel<br>      typed_config:<br>        &quot;@type&quot;: type.googleapis.com/envoy.extensions.access_loggers.filters.cel.v3.ExpressionFilter<br>        expression: &quot;(response.backend_latency &gt;= duration(&#39;2s&#39;))&quot;<br>  typed_config:<br>    &quot;@type&quot;: type.googleapis.com/envoy.extensions.access_loggers.file.v3.FileAccessLog<br>    path: /dev/stdout<br>    log_format:<br>      json_format:<br>        listener_name: https_ingress<br>        upstream_connection_id: &quot;%UPSTREAM_CONNECTION_ID%&quot;<br>        downstream_connection_id: &quot;%CONNECTION_ID%&quot;<br>        time: &quot;%START_TIME%&quot;<br>        request_protocol: &quot;%PROTOCOL%&quot;<br>        method: &quot;%REQ(:METHOD)%&quot;<br>        path: &quot;%REQ(X-ENVOY-ORIGINAL-PATH?:PATH)%&quot;<br>        scheme: &quot;%REQ(:SCHEME)%&quot;<br>        upstream_request_protocol: &quot;%UPSTREAM_PROTOCOL%&quot;<br>        status: &quot;%RESPONSE_CODE%&quot;<br>        response_code_details: &quot;%RESPONSE_CODE_DETAILS%&quot;<br>        request_time_msec: &quot;%DURATION%&quot;<br>        request_ttfb_msec: &quot;%RESPONSE_DURATION%&quot;<br>        response_flags: &quot;%RESPONSE_FLAGS%&quot;<br>        connection_termination_details: &quot;%CONNECTION_TERMINATION_DETAILS%&quot;<br>        user_agent: &quot;%REQ(USER-AGENT)%&quot;<br>        request_body_length: &quot;%BYTES_RECEIVED%&quot;<br>        bytes_sent: &quot;%BYTES_SENT%&quot;<br>        remote_addr: &quot;%DOWNSTREAM_REMOTE_ADDRESS_WITHOUT_PORT%&quot;<br>        remote_port: &quot;%DOWNSTREAM_REMOTE_PORT%&quot;<br>        local_addr: &quot;%DOWNSTREAM_LOCAL_ADDRESS_WITHOUT_PORT%&quot;<br>        local_port: &quot;%DOWNSTREAM_LOCAL_PORT%&quot;<br>        upstream_cluster: &quot;%UPSTREAM_CLUSTER%&quot;<br>        upstream_addr: &quot;%UPSTREAM_HOST%&quot;<br>        upstream_request_attempt_count: &quot;%UPSTREAM_REQUEST_ATTEMPT_COUNT%&quot;<br>        upstream_transport_failure_reason: &quot;%UPSTREAM_TRANSPORT_FAILURE_REASON%&quot;<br>        downstream_transport_failure_reason: &quot;%DOWNSTREAM_TRANSPORT_FAILURE_REASON%&quot;<br>        envoy_log_type: HTTP<br>        hostname: &quot;%REQUESTED_SERVER_NAME%&quot;</pre><p>Notice the CEL expression being used in the filter,</p><pre>response.backend_latency &gt;= duration(&quot;2s&quot;)</pre><p>You can extend this pattern to create more complex filters by combining multiple conditions. For example:</p><pre>expression: &gt;<br> response.backend_latency &gt;= duration(&quot;2s&quot;) &amp;&amp; <br> (response.code &gt;= 500 || request.headers[&quot;x-req-debug&quot;] == &quot;true&quot;)</pre><p>This would log requests that either took more than 2 seconds <strong>AND</strong> resulted in a 5xx error, or had a debug header set.</p><h4>Key Benefits of CEL</h4><ol><li><strong>Simplified Configuration:</strong> Replace complex nested filters with single expressions.</li><li><strong>Enhanced Access:</strong> Reach metrics and attributes not available in standard filters.</li><li><strong>Maintainable Code:</strong> Easier updates and changes to filtering logic<br>Performance: Linear-time evaluation for efficient processing.</li></ol><h4>Caveats</h4><p>When implementing CEL filters in Envoy, there are a few important considerations:</p><ol><li><strong>Production Readiness:</strong> While CEL filters are fully functional, they have not undergone extensive production testing at scale. Consider gradual rollout and thorough testing in your environment.</li><li><strong>Security Considerations:</strong> The security model of CEL extensions is still evolving. Only deploy in environments where you have full trust in both downstream clients and upstream servers.</li><li><strong>Trust Boundaries:</strong> CEL expressions have access to sensitive request and response data. Ensure your deployment environment maintains proper trust boundaries between services.</li></ol><h4>Beyond Access Logging</h4><blockquote>“CEL is not just for access logging — it’s a versatile tool for many Envoy configurations”</blockquote><p>CEL’s utility extends far beyond just access logging. Through Envoy’s <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/advanced/matching/matching_api">Unified Matchers</a>, you can use CEL expressions for:</p><ol><li><a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/advanced/matching/matching_listener#matching-filter-chains-in-listeners">Filter chain selection</a>: Select filter chains dynamically at connection time based on <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/advanced/matching/matching_api#extension-category-envoy-matching-network-input">network-level inputs</a>. The matching occurs once per connection, with automatic connection draining triggered by configuration changes but not by matcher updates.</li><li><a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/http/http_routing#routing-via-generic-matching">Route selection</a>: Configure routing using a <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/advanced/matching/matching_api#arch-overview-matching-api">generic match tree</a> that enables <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/advanced/matching/matching_api#arch-overview-sublinear-routing">sub-linear matching</a> on any header field. This provides significantly more flexibility and performance compared to traditional routing engines that were limited to :authority header based matching.</li><li><a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/security/rbac_filter#matcher">RBAC rule definition</a>: Define access control <a href="https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/rbac/v3/rbac.proto#envoy-v3-api-field-config-rbac-v3-rbac-policies">policies</a> using both network and <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/advanced/matching/matching_api#extension-category-envoy-matching-http-input">HTTP-level inputs</a>. <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/advanced/matching/matching_api#extension-category-envoy-matching-network-input">Network inputs</a> are available across all RBAC implementations (both <a href="https://www.envoyproxy.io/docs/envoy/latest/configuration/listeners/network_filters/rbac_filter">network</a> and <a href="https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/rbac_filter">HTTP</a> filters), while <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/advanced/matching/matching_api#extension-category-envoy-matching-http-input">HTTP-specific inputs</a> are exclusively available when using <a href="https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/rbac_filter">HTTP filters</a>.</li><li><a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/advanced/matching/matching_api#filter-integration">Conditional filter activation</a>: Enable dynamic filter behavior in HTTP environments using a wrapper protocol buffer. This allows you to associate matching rules directly with filter configurations for context-aware filter activation and behavior.</li></ol><h4>Looking Ahead</h4><p>Stay tuned for upcoming posts where we’ll dive into:</p><ol><li>Using CEL with <a href="https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/common/matcher/v3/matcher.proto">Unified Matchers</a></li><li>Advanced RBAC configurations</li><li>Dynamic routing with CEL</li><li>Real-world use cases and patterns</li></ol><h4>Key Takeaways</h4><ol><li>CEL provides a powerful, flexible way to create complex filtering rules.</li><li>Single expressions can replace multiple nested filters.</li><li>Linear-time evaluation ensures performance at scale.</li><li>CEL’s utility extends beyond just access logging.</li></ol><p>Are you using CEL in your Envoy setup? I’d love to hear about your use cases and experiences! If you need additional matchers or have specific scenarios you’re trying to solve, let me know in the comments. I’m actively working on extending our CEL matchers and your input would help prioritize what to build next.</p><p>This post is part of our ongoing series about Envoy proxy optimization and configuration. Follow along as we dive into topics like RBAC configurations, dynamic routing patterns, and more advanced use cases of Envoy’s powerful features. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50809f4c66cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling Envoy Proxy: How We Slashed Logging Costs by 65%]]></title>
            <link>https://agrawroh.medium.com/scaling-envoy-proxy-how-we-slashed-logging-costs-by-65-e73d922dea26?source=rss-3de2b8464006------2</link>
            <guid isPermaLink="false">https://medium.com/p/e73d922dea26</guid>
            <category><![CDATA[cost-savings]]></category>
            <category><![CDATA[envoy-proxy]]></category>
            <category><![CDATA[service-mesh]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[scaling]]></category>
            <dc:creator><![CDATA[Rohit Agrawal]]></dc:creator>
            <pubDate>Sun, 22 Dec 2024 14:40:15 GMT</pubDate>
            <atom:updated>2024-12-22T15:01:59.948Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CfeL5XKiYbf_gWRzzdtjgQ.png" /><figcaption>To log, or not to log — that is the question 🤔</figcaption></figure><p>At <a href="https://www.databricks.com/company/careers/engineering-at-databricks">Databricks</a>, we face a classic engineering dilemma: our <a href="https://www.envoyproxy.io/">Envoy proxies</a> generate invaluable access logs that help us debug network issues, but these same logs significantly impact performance and costs. In fact, our benchmarks showed that simply turning off access logs could double our throughput.</p><p>Here’s how we solved this challenge.</p><h4>The Setup: Our Envoy Architecture</h4><p>We deploy Envoy at multiple layers — as our main ingress proxy and as an egress filtering proxy. The <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/observability/access_logging">access logs</a> and metrics they emit are crucial for understanding network behavior. When a user workload fails, these logs help us quickly identify the root cause: whether it’s an <a href="https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/ext_authz_filter">ExtAuthZ</a> error, a <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/other_features/global_rate_limiting">rate-limit</a> breach, or an <a href="https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/rbac_filter">RBAC</a> rule violation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N95OmTM3mAro9C9pnDuHmA.png" /><figcaption>Our Ingress Envoy’s HTTP Filter Chain: Request Processing Flow</figcaption></figure><h4>The Challenge: Performance vs. Observability</h4><p>However, comprehensive logging comes at a steep price:<br>- Reduced throughput of Envoy proxies<br>- Significant processing overhead<br>- High storage costs</p><blockquote>In our independent benchmark testing, we discovered something striking: disabling access logs completely could boost overall throughput by up to 2x.</blockquote><h4>Our Solution: Strategic Logging</h4><p>The answer isn’t to abandon logging entirely — it’s to log strategically. Envoy provides powerful <a href="https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/accesslog/v3/accesslog.proto#config-accesslog-v3-accesslogfilter">filtering capabilities</a> that allow us to:<br>- Write different types of requests and responses to different access logs.<br>- Intelligently limit our logging footprint by filtering out noise.</p><h4>Understanding Envoy’s Log Filtering</h4><p>Envoy’s log filtering offers extensive options based on <a href="https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/accesslog/v3/accesslog.proto#envoy-v3-api-field-config-accesslog-v3-accesslogfilter-response-flag-filter">response flags</a>, <a href="https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/accesslog/v3/accesslog.proto#envoy-v3-api-field-config-accesslog-v3-accesslogfilter-status-code-filter">status codes</a>, <a href="https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/accesslog/v3/accesslog.proto#envoy-v3-api-field-config-accesslog-v3-accesslogfilter-duration-filter">request duration</a>. It’s also possible to use complex expressions using <a href="https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/accesslog/v3/accesslog.proto#envoy-v3-api-field-config-accesslog-v3-accesslogfilter-and-filter">AND</a>/<a href="https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/accesslog/v3/accesslog.proto#envoy-v3-api-field-config-accesslog-v3-accesslogfilter-or-filter">OR</a> operators.</p><p>For instance, instead of logging every <strong>200 OK</strong> response, we can focus on specific scenarios:<br>- High-latency requests (&gt; 500ms)<br>- Requests that got retried upstream<br>- All 4XX and 5XX responses for post-mortem analysis</p><h4>Implementation: Sample Filtering Configuration</h4><p>Here’s a real-world example of how we implemented some of these filters:</p><pre># This configuration achieves:<br># 1. Logs all errors (4XX, 5XX)<br># 2. Samples successful requests at a configurable rate<br># 3. Allows runtime modification of sampling rates<br>filter:<br>    or_filter:<br>      filters:<br>        - or_filter:<br>            filters:<br>              # Filter for specific status codes<br>              - status_code_filter:<br>                  comparison:<br>                    op: EQ<br>                    value:<br>                      default_value: 0<br>                      runtime_key: access-logs-eq-zero-status-code<br>              # Filter for error responses<br>              - status_code_filter:<br>                  comparison:<br>                    op: GE<br>                    value:<br>                      default_value: 400<br>                      runtime_key: access-logs-ge-400-status-codes<br>        # Sampling filter for remaining traffic<br>        - runtime_filter:<br>            percent_sampled:<br>              denominator: MILLION<br>              numerator: 1000000<br>            runtime_key: access-logs-sampling-rate<br>            use_independent_randomness: false</pre><h4>Results and Impact</h4><p>After implementing this strategic logging approach, we observed:</p><ul><li>Up to 80% reduction in the overall logging volume.</li><li>Up to 60% improvement in the proxy throughput.</li><li>Up to 65% decrease in logging storage costs.</li></ul><h4>Lessons Learned</h4><p>During this optimization journey, we learned several key lessons:</p><ol><li>Not all logs are created equal. Developers should focus on capturing anomalies and errors.</li><li>Runtime configurability is crucial for adapting to different traffic patterns.</li><li>Regular review of logging patterns helps identify opportunities for any further optimization.</li></ol><h4>Looking Ahead: Limitations and Future Improvements</h4><p>While Envoy’s filtering capabilities have helped us optimize our logging pipeline and increase the overall throughput, there are several limitations in the current system that drive our future roadmap:</p><ol><li><strong>Context-Aware Filtering:</strong> The system can’t make decisions based on historical data. For instance, we can’t implement rules like <em>“sample requests from an IP if its previous 200 OK response wasn’t sampled.”</em></li><li><strong>Dynamic Traffic Adaptation:</strong> Current filtering rules are static and can’t automatically adjust based on traffic patterns. For example, we can’t automatically increase sampling rates during low-traffic periods or decrease them during traffic spikes.</li><li><strong>Real-time Rule Updates:</strong> While Envoy supports runtime updates, changing filtering rules requires careful coordination and can’t be done in response to real-time traffic conditions.</li></ol><p>To address these limitations, we’re working on:</p><ol><li>Implementing dynamic sampling rates that adapt to traffic patterns.</li><li>Developing tools to analyze and optimize our sampling coverage.</li><li>Creating a feedback loop between our monitoring systems and Envoy configuration.</li></ol><p>We’re actively collaborating with the Envoy community to enhance these capabilities, especially around context-aware filtering and more sophisticated sampling strategies.</p><h4>Advanced Filtering</h4><p>While we’ve focused on basic filters in this post, Envoy also supports <a href="https://cel.dev/">Common Expression Language (CEL)</a> for more complex filtering needs.</p><p>We’ll deep dive into CEL expressions in a future post, as they deserve their own detailed exploration.</p><h4>Key Takeaways</h4><ol><li>Strategic logging can significantly improve performance while maintaining visibility.</li><li>Envoy’s filtering capabilities provide flexible control over logging<br>Regular measurement and adjustment of logging strategies is crucial.</li><li>Consider both immediate and future needs when designing logging systems.</li></ol><p>This is just the beginning of our journey in optimizing Envoy’s observability. Stay tuned for our next post about advanced filtering techniques using CEL expressions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e73d922dea26" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>