Optimize Endpoints

This guide shows you how to improve the performance of your Azu endpoints.

Response Caching

Cache frequently accessed data:

struct ProductsEndpoint
  include Azu::Endpoint(EmptyRequest, ProductsResponse)

  get "/products"

  CACHE_TTL = 5.minutes

  def call : ProductsResponse
    cache_key = "products:#{cache_params}"

    cached = Azu.cache.get(cache_key)
    return ProductsResponse.from_json(cached) if cached

    products = Product.all
    response = ProductsResponse.new(products)

    Azu.cache.set(cache_key, response.to_json, expires_in: CACHE_TTL)

    response
  end

  private def cache_params
    "page=#{params["page"]? || 1}&limit=#{params["limit"]? || 20}"
  end
end

HTTP Caching Headers

Set cache headers for client-side caching:

Pagination

Always paginate large collections:

Selective Field Loading

Only load required fields:

Eager Loading

Avoid N+1 queries:

Parallel Processing

Execute independent operations in parallel:

Compression

Compress large responses:

Connection Keep-Alive

Enable persistent connections:

Response Streaming

Stream large responses:

Async External Calls

Don't block on external services:

Request Timeouts

Set timeouts for operations:

Benchmark Endpoints

Measure endpoint performance:

See Also

Last updated

Was this helpful?