KrakenD Community Edition

repository·master·Indexed 25 days ago

https://github.com/krakend/krakend-ce

An open-source, ultra-high performance API Gateway designed for microservices and Backend For Frontend (BFF) implementations. It features content management, security (OAuth, JWT, Zero-trust), traffic control (rate-limiting, circuit breakers), and observability integration with Prometheus, Grafana, and OpenTelemetry. The gateway is extensible via Go plugins, Lua scripts, and Google CEL spec, and can be deployed using Docker or built from source.

Tokens
3.2K
Snippets
5
Records
23
Agent score
83%

What's inside KrakenD-CE

  1. Overview of KrakenD Technical Features

    master

    KrakenD is a high-performance API Gateway designed for microservices and Backend For Frontend (BFF) implementations. Key technical capabilities include:

    • Content Management: Aggregation, composition, filtering, and format transformation (e.g., XML to JSON).
    • Security: Support for Zero-trust, CORS, OAuth, JWT, HSTS, and various XSS/MIME-Sniffing protections.
    • Traffic Control: Throttling, multi-layer rate-limiting (including bursting and circuit breakers), and concurrent backend calls.
    • Observability: Telemetry integration with Datadog, Zipkin, Jaeger, Prometheus, and Grafana.
    • Extensibility: Support for Go plugins, Lua scripts, Martian, and Google CEL spec.
    • Protocols: SSL and HTTP2 ready.
  2. Build KrakenD from source

    master

    If you want to build the KrakenD binary yourself, you can use the provided Makefile.

    Ensure you have the correct Go version installed as specified in the Makefile. If you do not have Go installed locally, you can use the Docker-based build command which utilizes a Go container to perform the compilation.

  3. Run KrakenD using Docker

    master

    The fastest way to start KrakenD is by using the official Docker image. By default, it listens on port 8080. You can verify the gateway is running by checking the /__health endpoint.

    To use your own configuration, you must replace the default /etc/krakend/krakend.json file inside the container with your custom configuration file (which can be generated using the KrakenD Designer).

    docker run -it -p "8080:8080" krakend
  4. Configure custom 404 and 405 error bodies in Gin engine

    master

    You can customize the JSON response returned when a route is not found (404) or a method is not allowed (405) by adding an error_body to the ExtraConfig under the luragin namespace.

    The configuration structure follows this JSON pattern:

    {
      "extra_config": {
        "luragin": {
          "error_body": {
            "404": { "error": "Not Found", "status": 404 },
            "405": { "error": "Method Not Allowed", "status": 405 }
          }
        }
      }
    }
  5. Configure Flexible Config via environment variables

    master

    KrakenD CE supports flexibleconfig for advanced configuration management using templates, partials, and settings. To enable this mode, you must set the FC_ENABLE environment variable. When enabled, the following environment variables control the flexible configuration behavior:

    • FC_ENABLE: Enables flexible configuration.
    • FC_PARTIALS: Path to partial configuration files.
    • FC_TEMPLATES: Path to configuration templates.
    • FC_SETTINGS: Path to settings files.
    • FC_OUT: The output path for the processed configuration.
  6. Initialize a HandlerFactory with middleware

    master

    Use NewHandlerFactory to create a router.HandlerFactory that comes pre-configured with a standard middleware stack. The stack includes:

    • Rate limiting (ratelimit)
    • Lua scripting support (lua)
    • JOSE/JWT rejection (ginjose)
    • Metrics collection (metrics)
    • OpenCensus instrumentation (opencensus)
    • Bot detection (botdetector)

    To use the resulting factory, call it with an *config.EndpointConfig and a proxy.Proxy to obtain a gin.HandlerFunc for your endpoints.

  7. Initialize a BackendFactory with NewBackendFactory

    master

    Use NewBackendFactory to create a proxy.BackendFactory that automatically stacks all available KrakenD middlewares. This includes OAuth2 client credentials, HTTP cache, Martian, PubSub, AMQP, CEL, Lua, Rate-limiting, Circuit Breaker, and various metrics collectors (Metrics and OpenCensus).

    This function uses context.Background() internally.

  8. Configure observability with MetricsAndTracesRegister

    master

    Implement MetricsAndTracesRegister to define how metrics and traces are collected and exported. The default implementation (MetricsAndTraces) supports:

    • InfluxDB: For metric storage.
    • OpenCensus: For distributed tracing.
    • OpenTelemetry (OTel): For modern observability exporters.

    Note: The MetricsAndTraces implementation implements io.Closer to ensure telemetry resources are cleaned up during shutdown.

  9. Configure custom logging with LoggerFactory

    master

    Implement the LoggerFactory interface to control how KrakenD initializes its logging system. The default LoggerBuilder implementation attempts to set up logging in the following order of precedence:

    1. GELF: If configured in ExtraConfig.
    2. Logstash: If configured in ExtraConfig.
    3. Gologging: Standard structured logging.
    4. Stdout: Fallback to basic debugging output.
  10. Initialize a Gin engine with NewEngine

    master

    Use NewEngine to create a new Gin engine instance pre-configured with KrakenD defaults. This function automatically sets up:

    • Default handlers for NoRoute (404) and NoMethod (405).
    • Custom error bodies if defined in cfg.ExtraConfig under the luragin namespace.
    • httpsecure middleware registration.
    • lua router integration.
    • botdetector middleware registration.

    To customize the error response for 404 or 405 errors, provide an error_body object in your ExtraConfig using the luragin namespace.

    import (
    	"github.com/gin-gonic/gin"
    	"github.com/luraproject/lura/v2/config"
    	"github.com/luraproject/lura/v2/router/gin"
    )
    
    // Example usage pattern
    engine := krakend.NewEngine(cfg, opt)
  11. Register Service Discovery subscriber factories

    master
    Use RegisterSubscriberFactories to register all available service discovery (SD) adapters within the KrakenD ecosystem. This function initializes the internal registry of subscriber factories, allowing the system to resolve service names to network addresses (name and port) based on the configured SD mechanism (e.g., DNS SRV).
  12. Initialize a ProxyFactory with NewProxyFactory

    master

    Use NewProxyFactory to create a proxy.Factory that includes the default KrakenD proxy stack. This factory automatically wraps the provided BackendFactory with several middleware layers, including:

    • JSON Schema validation (jsonschema)
    • Common Expression Language (cel)
    • Lua scripting (lua)
    • Metrics collection (metrics)
    • OpenCensus instrumentation (opencensus)

    The returned factory is a proxy.FactoryFunc that, when called with an *config.EndpointConfig, builds a proxy.Proxy for that specific endpoint.