OpenResty runs the same NGINX core as NGINX and adds LuaJIT, ngx_lua, and ready-to-use Lua libraries, so you can run gateway logic in Lua. For pure proxying and TLS termination, throughput and latency are essentially the same, and vanilla NGINX is enough. When the gateway must query Redis at high concurrency, choose upstreams based on live data, or load certificates without a reload, OpenResty is the better fit.

You may already have an NGINX gateway in place: it receives requests, terminates TLS, and forwards traffic to backends, all reliably. But business requirements keep growing. New tasks gradually pile onto the gateway: check Redis to see whether an account is blocked, choose an upstream cluster based on the tenant, apply fine-grained limits based on an account or token quota for an AI or critical API, count streaming responses in real time, or fail over automatically when a backend goes down. The gateway that once just pointed traffic in the right direction now carries an increasing amount of business logic.

OpenResty is not the only way to do these things. Current NGINX, together with the official njs (NGINX JavaScript) module, auth_request, or custom C modules, can handle many dynamic requirements. But as logic grows and performance and low-level control matter more, problems emerge: nginx.conf and scattered scripts become harder to maintain; an external authentication service adds another network hop; and changing upstreams or certificates dynamically often requires a process reload. How do you test the code? Handle high concurrency? Diagnose an incident at night? These are exactly the problems OpenResty is designed to address.

This article uses a gateway scenario to explain the practical boundary between the two and when it makes sense to replace NGINX with OpenResty. For an overview, see What Is OpenResty? From Nginx and LuaJIT to Real-World Use Cases.

When the gateway is more than a traffic director

Suppose you want to add tenant authentication and dynamic routing to an API gateway. Each request must pass through these steps:

  1. Read the account identifier from the X-API-Key request header.
  2. Query Redis to confirm the account is active and retrieve its tenant configuration and backend nodes.
  3. Select an upstream dynamically based on the tenant tier; reject the request with the appropriate status if the account is disabled or the query fails.
  4. Count calls or quota, apply a rate limit when a threshold is reached, and forward the request if it passes.

One or two simple header checks or a lightweight HTTP subrequest can be handled with native configuration, njs, or auth_request. But when the gateway needs high-concurrency direct Redis access, layered caching to prevent stampedes, and real-time control of load balancing based on the returned data, a stitched-together solution quickly reaches its limits in performance and maintainability.

Put code in the gateway: how OpenResty helps

In OpenResty, you can attach Lua code to nearly every key NGINX phase, including ssl_certificate, rewrite, access, balancer, and body_filter.

The authentication and routing logic above might look like this:

location /api/ {
    access_by_lua_block {
        local api_key = ngx.req.get_headers()["X-API-Key"]
        if not api_key then
            return ngx.exit(401)
        end

        -- Use a reusable Lua module to query Redis without blocking, authorize, and choose a route
        local tenant_upstream, err = require("gateway.auth").verify_and_route(api_key)
        if not tenant_upstream then
            ngx.log(ngx.ERR, "auth failed: ", err)
            return ngx.exit(403)
        end

        -- Pass the selected upstream to NGINX for proxying in a later phase
        ngx.var.target_upstream = tenant_upstream
    }

    proxy_pass http://$target_upstream;
}

You do not have to put all the logic in the configuration file. Split it into independent Lua modules, such as gateway.auth above, and use version control for unit tests and code review just as you would for a regular backend application.

NGINX njs vs OpenResty Lua: where they differ

NGINX with njs can also run code and make asynchronous requests with ngx.fetch(). njs is a good fit for lightweight configuration extensions and simple HTTP calls. The distinction becomes clear as the gateway takes on heavier work:

  1. Nonblocking clients for native protocols: OpenResty provides the nonblocking cosocket API. When Lua queries Redis, MySQL, PostgreSQL, or Kafka, the waiting Lua coroutine yields and the NGINX worker can handle thousands of other concurrent requests. Native binary-protocol clients such as lua-resty-redis also provide connection pooling and have been proven under high concurrency for more than a decade, so everything need not be wrapped behind HTTP.
  2. Low-level control without reloads: With open-source NGINX, even if a script calculates new upstream nodes or an SSL certificate for a new tenant, taking control of connection retries and handshakes without reloading the process is difficult. OpenResty’s balancer_by_lua and ssl_certificate_by_lua can scale upstream nodes, implement custom retry policies, and deliver certificates for many domains dynamically in memory, without a reload.
  3. Ready-made gateway building blocks: Common needs such as combined leaky-bucket/token-bucket limits (lua-resty-limit-traffic), multi-level in-process LRU and shared-memory caching (lua-resty-mlcache), and active health checks are covered by established OpenResty libraries. You can assemble them instead of building everything from scratch.

When to use OpenResty instead of NGINX

Consider OpenResty when your NGINX gateway starts to need any of the following:

  • Deep integration with external stores and layered caching: The gateway must connect to Redis, databases, or message queues at high concurrency, using connection pools and multi-level caching that combines a per-worker LRU cache with shared memory (Shared Dict) to handle traffic spikes rather than making a simple HTTP authentication subrequest.
  • Fully dynamic low-level control without reloads: Upstream nodes change frequently, load balancing must respond to live business state, or TLS certificates for thousands of custom domains must be loaded dynamically. Frequent nginx -s reload operations cause too much connection churn or performance overhead.
  • Compute-heavy work or complex streaming: The gateway needs large-scale request/response rewriting, complex encryption, or chunk-by-chunk auditing and token counting for AI SSE responses, and needs LuaJIT performance or direct C-library calls through FFI.
  • Engineering discipline for gateway logic: Rules scattered across nginx.conf, small scripts, and external services have become hard to manage, and the team wants modular, testable application code in one place.

Conversely, if your gateway only handles fixed reverse-proxy rules and static files, or a few lines of njs can change headers, vanilla NGINX is enough. There is no need to change stacks just for the sake of it.

OpenResty lets you write business code in the gateway, so treat that code like application code. How should the gateway degrade when Redis times out? How should local caches be invalidated? How should code be released and rolled back? Those engineering questions still need careful answers.

OpenResty vs NGINX performance: does Lua make it slower?

Does Lua make OpenResty slower than vanilla NGINX? Is it faster than other NGINX extension approaches? It depends on the workload:

  1. Pure proxying: If neither side runs extra logic and both only proxy traffic and terminate TLS, throughput and latency are essentially the same—the same NGINX core runs underneath OpenResty.
  2. Dynamic business gateway: With frequent authentication, dynamic routing, data redaction, or streaming response processing, OpenResty often has an advantage over “NGINX + an external auth_request service” and interpreted lightweight scripts. It avoids serialization and communication across processes or the network. LuaJIT has a real just-in-time compiler and low-overhead coroutines, giving it strong CPU and garbage-collection performance under high concurrency and heavier logic.

Of course, LuaJIT cannot rescue a poor external dependency. If every request runs a slow query without local caching, throughput will still fall. If you benchmark with tools such as wrk, make sure both implementations run equivalent business logic and account for real variables such as cache hit rate and downstream timeouts.

How hard is a gradual migration from NGINX?

The migration burden is small. OpenResty is fully compatible with standard NGINX, so existing nginx.conf, server, location, and upstream configurations can usually be reused as-is. The safest approach is to replace the gateway runtime first while keeping the existing pure-proxy configuration unchanged. After it has stabilized, add or replace Lua logic in specific location blocks.

Before switching, check that third-party modules compiled for the original NGINX, dynamic module paths, runtime permissions, and system startup scripts all match the target OpenResty environment—even if both launch commands are named nginx.

In practice, export and compare the original instance’s nginx -V build options. In a test environment, replay representative traffic and verify error handling, timeout settings, log formats, and upstream connection pools. Complete the rollout after a canary has passed.

Frequently asked questions

Is OpenResty faster than NGINX?

It depends on the workload. For pure proxying and TLS termination, throughput and latency are essentially the same, because the same NGINX core runs underneath OpenResty. With frequent authentication, dynamic routing, or streaming response processing, OpenResty often has an advantage over NGINX with an external auth_request service, because it avoids serialization and communication across processes or the network. A slow external dependency without local caching still lowers throughput.

Can NGINX njs do what OpenResty does?

For lightweight configuration extensions and simple HTTP calls, yes. The difference appears as the gateway takes on heavier work. OpenResty’s nonblocking cosocket API lets Lua query Redis, MySQL, PostgreSQL, or Kafka without blocking the worker, and clients such as lua-resty-redis provide connection pooling. balancer_by_lua and ssl_certificate_by_lua control upstreams and certificates without a reload, and established libraries cover rate limiting, caching, and health checks.

Do I need OpenResty for a simple reverse proxy?

No. If your gateway only handles fixed reverse-proxy rules and static files, or a few lines of njs can change headers, vanilla NGINX is enough. Consider OpenResty when the gateway needs deep integration with external stores, dynamic control without reloads, compute-heavy or streaming work, or modular, testable gateway code.

Summary and next steps

If vanilla NGINX with simple configuration or lightweight scripts still handles the job, keep it. If gateway logic is growing and you are hitting limits around performance, external-store connection pools, or dynamic control without reloads, OpenResty is worth trying.

This article is part of the OpenResty tutorial series. To try it, read the practical guide Migrating from NGINX to OpenResty: Configuration Checks, Parallel Validation, and Rollback, or first learn about OpenResty’s components.

If you like this tutorial series, subscribe to this blog and our YouTube channel.

About The Author

Yichun Zhang (GitHub handle: agentzh), is the original creator of the OpenResty® open-source project and the CEO of OpenResty Inc..

Yichun is one of the earliest advocates and leaders of “open-source technology”. He worked at many internationally renowned tech companies, such as Cloudflare, Yahoo!. He is a pioneer of “edge computing”, “dynamic tracing” and “machine coding”, with over 22 years of programming and 16 years of open source experience. Yichun is well-known in the open-source space as the project leader of OpenResty®, adopted by more than 40 million global website domains.

OpenResty Inc., the enterprise software start-up founded by Yichun in 2017, has customers from some of the biggest companies in the world. Its flagship product, OpenResty XRay, is a non-invasive profiling and troubleshooting tool that significantly enhances and utilizes dynamic tracing technology. And its OpenResty Edge product is a powerful distributed traffic management and private CDN software product.

As an avid open-source contributor, Yichun has contributed more than a million lines of code to numerous open-source projects, including Linux kernel, Nginx, LuaJIT, GDB, SystemTap, LLVM, Perl, etc. He has also authored more than 60 open-source software libraries.