(LINUX) LINUX (2025)

OpenResty/LuaJIT - The fastest backend technology ever exists.

1. LuaJIT is bridge between internal Nginx structures and allow directly manupulate Nging features.

In this year I'm faced in real project with fantestic technology - LuaJIT compiler what allow scripting internal Nginx features:


Feature How OpenResty Uses It
Event-Driven Model Lua runs asynchronously (no blocking I/O).
Shared Memory Zones Lua scripts share data across workers (lua_shared_dict).
Subrequests Lua can spawn internal HTTP requests (ngx.location.capture).
TCP/UDP Stream Lua handles non-HTTP traffic (e.g., proxies, game servers).

Speed of this technology is fantastic, because this is C-brigge directly embedded to handle Nginx hook and Nginx features.


Nginx Phase OpenResty Lua Hook What You Can Do
Rewrite Phase rewrite_by_lua* Modify URLs, redirects (before routing).
Access Phase access_by_lua* Authentication, rate limiting.
Content Phase content_by_lua* Generate dynamic responses (bypass Nginx's static handler).
Header Filter Phase header_filter_by_lua* Modify HTTP headers before sending.
Body Filter Phase body_filter_by_lua* Modify response body (e.g., HTML sanitization).
Log Phase log_by_lua* Custom logging (e.g., analytics).

   1:  
   2:  -- Shared memory across all workers
   3:  http {
   4:      lua_shared_dict my_cache 10m;  
   5:      server {
   6:          location /get {
   7:              content_by_lua_block {
   8:                  local cache = ngx.shared.my_cache
   9:                  cache:set("key", "value", 60)  -- Set with TTL
  10:                  ngx.say(cache:get("key"))      -- Get value
  11:              }
  12:          }
  13:      }
  14:  }
  15:    

   1:  
   2:  -- Non-Blocking Database Query
   3:  location /user {
   4:      content_by_lua_block {
   5:          local mysql = require "resty.mysql"
   6:          local db = mysql:new()
   7:          db:connect({ host = "127.0.0.1", user = "root" })
   8:          local res = db:query("SELECT * FROM users")  -- Async!
   9:          ngx.say(res[1].username)
  10:      }
  11:  }
  12:    

   1:  
   2:  -- conditionally transform data before Nginx’s C core sees it
   3:  location /api {
   4:    access_by_lua_block {
   5:      if ngx.var.arg_token ~= "secret" then
   6:        ngx.exit(403)  -- Reject before C code runs
   7:      end
   8:    }
   9:    proxy_pass http://backend;  -- Nginx C core takes over
  10:  }
  11:    

Lua language allow diredctly use C-functions exposed by Nginx.

   1:  
   2:  // Nginx C module exposing a function to Lua
   3:  static ngx_int_t ngx_http_lua_hello(ngx_http_request_t *r) {
   4:    ngx_http_lua_ctx_t *ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module);
   5:    lua_pushstring(ctx->lua, "Hello from C!");
   6:    return NGX_OK;
   7:  }
   8:    

2. Fantesctic speed.

This is about speed (LUA at least 10 times faster than Javascript !!! and twice faster than C++ !!!):


Backend Avg. RPS (Plain Text) Latency (ms) Key Strengths
C (Manual) 200K - 300K+ 0.1 - 1ms Direct hardware access, no overhead
🔥 OpenResty (Lua) 150K - 250K+ 0.5 - 2ms Nginx event loop + LuaJIT (C-like speed)
🚀 Rust (Actix/Axum) 120K - 200K+ 1 - 3ms Zero-cost abstractions, no GC pauses
🦀 C++ (Boost.Beast) 100K - 180K+ 1 - 4ms High performance with OOP features
🚙 Go (Gin/Fiber) 80K - 150K+ 2 - 5ms Goroutines (easy concurrency), fast GC
🟪 C# (ASP.NET Core) 50K - 100K+ 3 - 10ms Great for enterprise, strong ecosystem
🐘 PHP (Laravel/Swoole) 30K - 70K 5 - 15ms Web-first design, huge CMS ecosystem
🐢 Node.js (Express) 10K - 30K 5 - 20ms Single-threaded (bottlenecked by JS event loop)
💩 Python (Django/Flask) 5K - 20K 10 - 50ms Developer productivity, data science

3. Term.


Feature Lua (Standard) LuaJIT (FFI) OpenResty (Nginx + LuaJIT)
Type Language Lua compiler/runtime Nginx + LuaJIT platform
Speed Slow Very fast JIT Extremely fast Nginx + JIT
Use Case General scripting High-perf Lua Web backends, proxies
Ecosystem Small Small (but fast) Rich Nginx modules + Lua
C Integration Lua C API (manual bindings) Direct FFI (no bindings) FFI + Nginx C modules
Performance Slow (Lua ↔ C marshaling) Near-native speed Near-native speed
Use Case Embedding Lua in C apps High-perf Lua+C apps Web/API servers with C extensions

4. Lua is extremely easy language.

Language Difficulty Why? Best For
Lua ⭐️ (Very Easy) Tiny syntax, no OOP, minimal stdlib. Feels like "shell scripting." Embedding (games, Nginx), quick scripts
VB.NET ⭐️ (Very Easy) Simple English-like syntax, verbose and understandable Web backend, Windows and Linux apps, any business applications
Python ⭐️⭐️ (Easy) Readable, huge stdlib, but indentation-sensitive Beginners, data science, automation
PHP ⭐️⭐️⭐️ (Medium) Simple to start but inconsistent standard library, many legacy quirks Web development, CMS systems (WordPress)
C# ⭐️⭐️⭐️ (Medium) Well-structured but requires understanding of .NET ecosystem Enterprise applications, Windows development, games (Unity)
Go ⭐️⭐️⭐️ (Medium) Simple syntax but rigid (no generics early), manual error handling Microservices, CLI tools, cloud applications
JavaScript ⭐️⭐️⭐️⭐️ (Medium-Hard) Weird quirks (this, == vs ===), async/await, ecosystem fatigue Web frontend/backend (Node.js)
Java ⭐️⭐️⭐️⭐️ (Medium-Hard) Verbose syntax, complex build systems, enterprise patterns Enterprise systems, Android apps (historically)
C++ ⭐️⭐️⭐️⭐️ (Hard) Manual memory management, complex standard library, multiple paradigms Game engines, high-performance systems
Rust ⭐️⭐️⭐️⭐️⭐️ (Very Hard) Ownership/borrowing, lifetimes, strict compiler High-perf systems, safety-critical apps

Language Pros Cons (Compared to Lua) Unique Aspects Main Challenges
Lua
  • Extremely lightweight (under 200KB)
  • Minimal syntax (only 21 keywords)
  • Easy C integration via Lua API
  • Portable across platforms
  • Limited standard library
  • No native OOP support
  • 1-based indexing (unusual for most developers)
  • Tables as universal data structure (replace arrays, objects, etc.)
  • Coroutines for cooperative multitasking
  • Metatables for operator overloading
  • Debugging complex table structures
  • Lack of type checking
VB.NET
  • English-like readable syntax
  • Excellent for rapid application development
  • Full access to .NET Framework
  • Strong legacy codebase support
  • Case-insensitive (unusual for modern languages)
  • Verbose syntax (e.g., End If)
  • Declining industry adoption
  • XML literals (directly in code)
  • Late binding support
  • Handles legacy COM objects well
  • Transitioning to other .NET languages
  • Modern web development limitations
Python
  • Intuitive syntax (e.g., for x in list)
  • Huge ecosystem (Django, Flask, NumPy, Pandas)
  • Excellent readability
  • Dynamic typing → runtime errors
  • Global Interpreter Lock (GIL) limits threading
  • Performance overhead
  • List comprehensions for concise data transformations
  • Extensive standard library ("batteries included")
  • Duck typing and magic methods (__init__, __str__)
  • Version fragmentation (Python 2 vs 3)
  • Packaging and dependency management
  • Multiprocessing vs multithreading complexity
PHP
  • Web-specific built-in functions
  • Huge CMS ecosystem (WordPress, Drupal)
  • Simple deployment (shared hosting)
  • Improved performance in PHP 8.x
  • Inconsistent function naming (strpos vs str_replace)
  • Historical security concerns
  • Mixed OOP/procedural paradigms
  • Superglobals ($_GET, $_POST)
  • Built-in template engine alternative (<?php ?> syntax)
  • Magic methods (__construct(), __get())
  • Legacy code compatibility issues
  • Type juggling behaviors
C#
  • Excellent IDE support (Visual Studio)
  • Strong typing with type inference
  • Modern language features (LINQ, async/await)
  • Cross-platform with .NET Core
  • Verbose compared to scripting languages
  • Complex ecosystem (.NET Framework vs Core)
  • Windows-centric history
  • Properties (getters/setters as first-class citizens)
  • Language Integrated Query (LINQ)
  • Attributes for metadata
  • Understanding the CLR and garbage collection
  • Asynchronous programming patterns
Go
  • Fast compilation
  • Goroutines (easy concurrency model)
  • Simple deployment (single binaries)
  • Verbose error handling
  • Less expressive (e.g., no generics pre-1.18)
  • Limited abstraction capabilities
  • Channels for goroutine communication
  • Built-in testing and benchmarking
  • Cross-compilation to multiple platforms
  • Lack of traditional exceptions
  • Immature dependency management
  • Error-prone zero value initialization
JavaScript
  • Runs everywhere (browser/server)
  • Async/await (modern asynchronous patterns)
  • Vibrant npm ecosystem
  • undefined/null hell
  • Prototypal inheritance (confusing for class-OOP developers)
  • Type coercion surprises ("2" + 2 = "22")
  • Closures and first-class functions
  • Event loop for non-blocking I/O
  • Modern ES6+ features (arrow functions, destructuring)
  • this binding complexities
  • Callback hell in legacy code
  • Toolchain fatigue (Babel, Webpack, etc.)
Rust
  • No garbage collector + memory safety
  • Blazing fast performance
  • Fearless concurrency
  • Steep learning curve
  • Complex lifetimes
  • Compile-time safety checks can feel restrictive
  • Ownership system for memory safety
  • Pattern matching with match
  • Zero-cost abstractions
  • Borrow checker frustrations
  • Long compile times for large projects
  • Limited IDE support compared to mature languages

5. Lua syntax.

And this is syntax of LUA language:


Lua Syntax VB.NET Equivalent
Variables and Assignment
x = 10 Dim x As Integer = 10
name = "John" Dim name As String = "John"
a, b = 1, 2 -- Multiple assignment Dim a As Integer = 1, b As Integer = 2
Control Structures
if x > 10 then
  print("Big")
end
If x > 10 Then
  Console.WriteLine("Big")
End If
if x > 10 then
  print("Big")
else
  print("Small")
end
If x > 10 Then
  Console.WriteLine("Big")
Else
  Console.WriteLine("Small")
End If
for i = 1, 10 do
  print(i)
end
For i As Integer = 1 To 10
  Console.WriteLine(i)
Next
while x < 10 do
  x = x + 1
end
While x < 10
  x += 1
End While
repeat
  x = x - 1
until x <= 0
Do
  x -= 1
Loop Until x <= 0
Functions
function add(a, b)
  return a + b
end
Function Add(a As Integer, b As Integer) As Integer
  Return a + b
End Function
local function foo()
  -- local function
end
Private Sub Foo()
  ' private method
End Sub
Tables (Lua) vs Collections (VB.NET)
t = {1, 2, 3} -- Array-like table Dim list As New List(Of Integer) From {1, 2, 3}
t = {name="John", age=30} -- Dictionary-like table Dim dict As New Dictionary(Of String, Object) From {{"name", "John"}, {"age", 30}}
print(t[1]) -- Access array element (1-based) Console.WriteLine(list(0)) ' 0-based index
print(t.name) -- Access table field Console.WriteLine(dict("name"))
Error Handling
local ok, err = pcall(function()
  error("oops")
end)
if not ok then
  print(err)
end
Try
  Throw New Exception("oops")
Catch ex As Exception
  Console.WriteLine(ex.Message)
End Try
Object-Oriented Programming
-- Lua OOP using tables
Person = {name="Unknown"}
function Person:new(o)
  o = o or {}
  setmetatable(o, self)
  self.__index = self
  return o
end
' Native VB.NET class
Public Class Person
  Public Property Name As String = "Unknown"
  Public Sub New()
  End Sub
End Class
p = Person:new({name="John"})
print(p.name)
Dim p As New Person With {.Name = "John"}
Console.WriteLine(p.Name)

6. My real project.

So, I'm happy tu use this language in practice to made refactoring some project made on this technology.



More details and continue in page Key points to working with Nginx LUA scripts - location of Nginx config and log, LuaJIT version, cache LUA scripts, debug and logging LUA, testing with CURL, LUA modules scope, LUA packages, Table type variable, working with Redis and MySQL.




Linux context:



Comments ( )
Link to this page: http://www.vb-net.com/OpenResty/Index.htm
< THANKS ME>