Cosockets and Non-Blocking TCP
Use ngx.socket.tcp for async backend connections in content_by_lua.
Cosockets and Non-Blocking TCP is a free Lua Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Are Cosockets?
OpenResty cosockets are non-blocking TCP/UDP sockets that integrate with Nginx's event loop. When waiting for data, they yield the coroutine, freeing the worker to handle other requests.
Creating a TCP Cosocket
Use ngx.socket.tcp() to create a cosocket. Connect, send, and receive all yield automatically when I/O would block.
-- content_by_lua_block
local sock = ngx.socket.tcp()
local ok, err = sock:connect("redis.local", 6379)
if not ok then
ngx.log(ngx.ERR, "Connect failed: ", err)
return ngx.exit(500)
endSending Data
sock:send(data) sends a string. Returns bytes sent or nil + error.
local bytes, err = sock:send("PING\r\n")
if not bytes then
ngx.log(ngx.ERR, "Send error: ", err)
endReceiving Data
sock:receive(pattern) reads data. Patterns: "*l" reads a line, "*a" reads all until close, a number reads exactly N bytes.
local data, err = sock:receive("*l")
if not data then
ngx.log(ngx.ERR, "Receive error: ", err)
return ngx.exit(500)
end
ngx.say("Response: " .. data)Setting Timeouts
Set connect, send, and receive timeouts to prevent hanging.
sock:settimeout(1000) -- 1 second timeout
-- or separate timeouts:
sock:settimeouts(1000, 5000, 5000) -- connect, send, receive (ms)Connection Pool
sock:setkeepalive(timeout, pool_size) puts the socket back in a pool for reuse. Crucial for Redis/MySQL performance.
sock:setkeepalive(60000, 100) -- 60s timeout, pool size 100Making an HTTP Request
Implement a simple HTTP/1.0 GET request using a cosocket.
local function httpGet(host, path)
local sock = ngx.socket.tcp()
sock:connect(host, 80)
sock:send("GET " .. path .. " HTTP/1.0\r\nHost: " .. host .. "\r\n\r\n")
local resp = sock:receive("*a")
sock:close()
return resp
endUDP Cosocket
ngx.socket.udp() creates a UDP cosocket. Useful for statsd metrics reporting.
local udp = ngx.socket.udp()
udp:setpeername("statsd.local", 8125)
udp:send("requests:1|c")Error Handling Pattern
All cosocket methods follow the Lua convention: nil + error string on failure. Always check both return values.
Cosocket Limitations
Cosockets cannot be used in: init_by_lua, set_by_lua, header_filter_by_lua. Use them only in content, access, and rewrite phases.
Performance Comparison
Cosockets achieve the same throughput as raw epoll-based C code because they directly use Nginx's I/O machinery. No extra thread or process overhead.
Cosocket Question
What happens when a cosocket is waiting for data from a slow server?
Recap: Cosockets and Non-Blocking TCP
OpenResty cosockets provide non-blocking TCP/UDP that yields on I/O, enabling high concurrency. Use setkeepalive for connection pooling. Set timeouts to avoid hanging. Only available in content/access/rewrite phases.
Frequently asked questions
Is the “Cosockets and Non-Blocking TCP” lesson free?
Yes — the full text of “Cosockets and Non-Blocking TCP” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.
What will I learn in “Cosockets and Non-Blocking TCP”?
Use ngx.socket.tcp for async backend connections in content_by_lua. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Lua Academy?
No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Cosockets and Non-Blocking TCP” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Lua Academy lesson?
Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- OpenResty Architecture
- Handling HTTP Requests in Lua
- Cosockets and Non-Blocking TCP
- Shared Memory Dictionaries