Lua Academy · Lesson

Cosockets and Non-Blocking TCP

Use ngx.socket.tcp for async backend connections in content_by_lua.

Lesson 3 of 413 steps

Cosockets and Non-Blocking TCP is a free Lua Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, and your progress syncs across the web and the CoddyKit app. The Lua Academy course includes 4 lessons in total.

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)
end

Sending 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)
end

Receiving 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 100

Making 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
end

UDP 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.

Free to start

Learn Lua with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
40
Lessons
159

Frequently Asked Questions

Is the “Cosockets and Non-Blocking TCP” lesson free?

Yes — any 3 lessons of the Lua Academy learning path, including “Cosockets and Non-Blocking TCP”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Lua Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

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

  1. OpenResty Architecture
  2. Handling HTTP Requests in Lua
  3. Cosockets and Non-Blocking TCP
  4. Shared Memory Dictionaries
← Back to Lua Academy