Leverage OpenResty to craft a dynamic load balancer with Lua, allowing requests to be routed based on their payloads.
OpenResty provides a powerful integration with Lua scripting, enabling unique ways to manipulate HTTP traffic. This project harnesses that power to inspect request payloads and intelligently decide the routing destination. The main goal is to create a dynamic, flexible, and context-aware load balancing mechanism.
-
Inspecting the Request: The access_by_lua_block directive is utilized to extract the request body. Once obtained, it's stored in ngx.ctx under the
body_data
key as a string. -
Determining the Destination: The balancer_by_lua_block directive accesses the stored
body_data
. Using cjson to parse the string to JSON, it identifies the appropriate host (based on thehost
key) and routes the request accordingly.
Environment Variables:
SERVER_A
: Internal URL for one of the potential routing destinations.SERVER_B
: Internal URL for another potential routing destination.
These variables help configure and differentiate the target endpoints, giving the load balancer its choices of servers to route traffic to. It can be adapted to multiple servers, this repository servers as a proof-of-concept only.
- Clone this repository and navigate to its directory.
cp docker-compose.override.example.yml docker-compose.override.yml
.cp .env.sample .env
.- Set the required environment variables
SERVER_A
andSERVER_B
accordingly. docker-compose up
, your service will be available athttp://localhost:3000
.
Improvements, bug fixes, and optimizations are always welcome! If you're looking to contribute, please fork the repository and submit a pull request.