Stackable Continuation Queues


cqueues is a type of event loop for Lua, except it's not a classic event loop. It doesn't use callbacks—neither as part of the API nor internally—but instead you communicate with an event controller by the yielding and resumption of Lua coroutines using objects that adhere to a simple interface.

cqueues are also stackable. Each instantiated cqueue is a pollable object which can be polled from another cqueue, or another event loop system entirely. The design is meant to be unintrusive, composable, and embeddable within existing applications—such as Apache or Nginx—or used standalone. It maintains no global state and never blocks your thread of execution.

cqueues includes a sockets library with DNS, buffering, end-of-line translation, SSL/TLS, and descriptor passing support builtin. Domain querying, connection establishment, and SSL negotiation are handled transparently as part of a state machine entered with every I/O operation, so users can read and write immediately upon instantiating the object, as if opening a regular file.

cqueues also includes modules for handling signals, threads, and file change notifications using native kernel facilities—such as signalfd on Linux, or Solaris PORT_SOURCE_FILE for file events—and accessible through easy to use interfaces which abstract the different kernel facilities.

Additional modules include a light-weight user-defined event system using the condition variable pattern, and a comprehensive interface for DNS querying.

cqueues is almost entirely self-contained, with the sole external dependencies being OpenSSL and, of course, Lua (Lua 5.2 or LuaJIT). However, it only works on Linux, NetBSD, OpenBSD, FreeBSD, Solaris, OS X, and derivatives. The concept is not portable to Windows because Windows lacks an analog to the pollable event queues of modern Unix systems. Libraries which try to abstract the two approaches—event readiness signaling versus event completion—invariably produce a pallid least common denominator library suffering all the weaknesses and enjoying none of the strengths of each approach.

cqueues is presently being used in production for several high-traffic services. However, I try to "release early, release often". Caveat emptor.


Comprehensive usage is documented in the cqueues Userguide PDF. For easy browsing use a PDF viewer with a side tab for the table of contents, such as on OS X.

See examples/ in the project tree for example scripts.

A simple client example showing SSL and cqueue controller nesting:

local cqueues = require("cqueues")
local socket = require("cqueues.socket")

local con = socket.connect("", 443)

local inner =
local outer =

	con:write("GET / HTTP/1.0\n")

	for ln in con:lines() do



A simple multiplexing echo server:

local cqueues = require("cqueues")
local socket = require("cqueues.socket")

local srv = socket.listen("", 8000)
local loop =

	for con in srv:clients() do
			for ln in con:lines("*L") do




Add interfaces for handling HTTP chunked transfer encoding, including when used simultaneously with multipart message support. Example: socket:setchunk(1234). This will set a read barrier--similar to how datagram support is handled--which causes block- and line-buffered reads to complete early when the barrier is reached.

Add file globbing to notify module.

Add socket read mode which specifies a Lua string pattern, e.g. "^%d+". Alternatively, finish LPegK work.

Integrate our timing wheel library for O(1) timeouts, replacing the LLRB implementation.

Employ O_EVTONLY on OS X so file change notifications don't prevent unmounting a drive.

Check PID in cqueues:step and reconstruct our kernel event queue if the application forked.

Return unique ID as second return value from cqueues:wrap and cqueues:attach. And return this ID from the cqueues:errors and similar interfaces so it's easier to detect and handle which coroutine failed.



Support OpenSSL 1.1 API. (@daurnimator)

Support clock_gettime with macOS Sierra / XCode 8.0. (Reported by @ziazon)

Support accept4 and paccept for atomic O_CLOEXEC. (@daurnimator)

Remove assert which aborted process when attempting to resume a dead coroutine as it doesn't necessarily signal process corruption. (@daurnimator)

Enable IPv6 AAAA queries in socket.connect.

Support passing Lua 5.3 integers as arguments to thread.start. (Reported by and preliminary patch from @daurnimator)

Basic SOCK_SEQPACKET support. (@daurnimator)

Tagged release rel-20161018 (9e2a3bcce5fc916960958bfdd5d9364a36534ece).


Allow yielding through cqueues:step. Patch by daurnimator.

Use SSLv23_server_method instead of SSLv3_server_method when guessing the TLS handshake mode—server or client—as many OpenSSL forks have deprecated or removed SSLv3-specific APIs. Fix from daurnimator.

Support SO_BROADCAST. Fix from daurnimator.

Fix v6only flag. Fix from daurnimator.

Tagged release rel-20160316 (b3705932920d7d597ad493f2810f47eda9e49322).


Fix bugs with getsockname and getpeername—AF_UNIX sockaddr length can vary considerably based on system call and operating system. Report and fixes from daurnimator. See for extended description of varying behavior.

Fix to socket.fdopen for regular files. Report and fix from daurnimator.

Allow non-string error objects to be returned from cqueues:step, et al. Fix from daurnimator.

Set contoller alert on cancellation to ensure any controller polling on that controller wakes up. Report by daurnimator.

Enhance accept to take an options argument. Fix from daurnimator.

Fix wrong order of parameters to fcntl in socket.dup.

Set errno when returning from BIO hooks as OpenSSL expects unrecoverable, generic error values to be in errno. Report by daurnimator.

Fix stack offsets in config:getlookup and config:getsearch. Report and fixes from tibboh.


Replace remaining uses of strerror with our thread-safe cqs_strerror macro.


Add autoflush support, enabled by default. When enabled, each logical read executes concurrently with an opportunistic flush, as if each non-blocking read attempt within the :read method were proceeded by :flush(0). When initiating TLS, the output buffer is fully flushed before initiating TLS, as-if :flush were called before :starttls.

Add pushback support, enabled by default. The first call to :starttls pushes all data in the input buffer back to the socket layer so it's read as part of the TLS handshake. This prevents smuggling of data into the secure phase of the session when upgrading to TLS, and also supports protocols which pipeline TLS handshake data with commands, as with XMPP Quickstart.

Ignore EOPNOTSUPP when trying to reset SO_REUSEPORT.


Add support for POLLPRI.

Fix Solaris Ports controller alerts.

Add support for eventfd for controller alerts.

Synchronize dns.c with upstream.

Various bug fixes.


:step, :loop, and :errors now return additional error information.


Use newproxy to detect object leaks in Lua 5.1/LuaJIT because Lua 5.1 language doesn't support __gc metamethods on tables. (daurnimator)


Add IPV6_V6ONLY support.

Rename undocumented socket.fdopen to socket.dup, and add socket.fdopen which takes ownership of the specified descriptor number. (Previously socket.fdopen would dup the descriptor.)


Wrap .sa_bind option of low-level socket library.

Optimize the way we put a controller in a ready state when signaling a condition variable.

Put a controller into a ready state when wrapping a function or attaching a coroutine.

Support Lua 5.3.

Tagged release rel-20150119 (56fd893388f592fa2e8f9cb91b99231b1ba8a23e).


Allow :events methods to return event set as integer bitset.

Fix NULL-dereference when calling :connect method on a socket created using socket.pair or socket.fdopen.

Fix cqueues.poll when polling outside of a managed coroutine.


Fix build dependency where M4 fails but the command line still creates the target. On subsequent invocations make thinks the target is satisfied.

Handle numeric hosts differently so that socket.listen doesn't try to build a resolver. On OS X when the network is not connected /etc/resolv.conf doesn't exist, so building a resolver results in an ENOENT error. This prevented listening on the loopback,, or ::1 when the network was disconnected.


Add TLS Server Name Indication (SNI) support. SNI is enabled by default, using the socket.connect host name. An explicit host name can be specified, or SNI can be disabled, by setting the .sendname socket option. See the cqueues Userguide PDF for more information.


Fix out-of-bounds write when reading inotify events, reported by Timo Teräs.


Fix compilation on NetBSD 5.1, which lacks constant NAN definition.

Make function optional.

Fix :recvfd to handle no descriptor in message.

Document promise module.

Tag rel-20140729 (622b5baa1115f634408182660e668cb76a59d316).


Add ability to pass functions as arguments to thread start routine. For C functions dladdr(3)+dlopen(3) is used to anchor the function in memory, in case the initiating thread later unloads the module. This is the same mechanism used when installing lock handlers in OpenSSL.


Pass on any additional arguments to cqueues:wrap when first resuming. Obviates the need to create an expensive closure every time you want to execute a task asynchronously.

Add promise module. Unlike JavaScript's promise interface, it's simple as it doesn't need to supplement for the inability to write logically synchronous code. It's more similar to C++11's promise/future interface, with :set, :get, and :wait, plus __call and __tostring metamethods.

Add cqueues.auxlib module, including new yieldable tostring implementation. Moved cqueues.assert, cqueues.resume, and cqueues.wrap to auxlib. Add auxlib.assert3, .assert4, etc, for assertions which call error() with a greater stack level. Add auxlib.filesresult, which converts the socket API return protocol to Lua's file API return protocol (specifically, error string followed by system error number).


Add maxerrs limit to catch unchecked error loops. Unchecked error loops are more likely to happen now that errors are repeated until cleared.

Add :setmaxerrs method to change default unchecked error limit of 100.


Add resolver pool module.

Fix SRV parsing bug in DNS library.

Update root nameserver hints within DNS library.


Don't abort process on assert(3) when caller improperly calls dns_res_check after dns_res_fetch, which happens when calling resolver:fetch multiple times.


Add SO_REUSEPORT support.


Text-mode block reads now should behave just like C's stdio. That is, if 1024 bytes are requested, then 1024 bytes are returned, which may have necessitated reading more than 1024 bytes from the socket given any EOL translations or to ensure a trailing carriage return is not followed by a linefeed. Previously all block reads were performed as-if in binary mode, without any EOL translation.

Add a read mode for MIME boundaries. Passing a string with the prefix of -- will read blocks of data up to the specified MIME boundary. Any trailing CRLF or LF is stripped from the last block, regardless of input mode, as that's part of the boundary syntax. If text mode is enabled then blocks of multiple, EOL-translated lines are returned together, up to the maximum limit set by the greater of :setbufsiz and :setmaxline, but usually less than that to avoid splitting lines unnecessarily. In binary mode blocks of a fixed sized are returned (as specified by :setbufsiz), except for the last block, which might be less than the block size.

Add socket.debug.lua, which contains unit tests and, in the future, auxiliary interfaces for debugging.


Add wrappers to coroutine.resume and coroutine.wrap, which support multilevel yielding on polling. This permits code inside a user code coroutine to still poll I/O without interfering with the resume/yield protocol of the user code. But these wrappers are not monkey patched into the current environment, so they must be used explicitly, or manually assigned as replacements to coroutine.resume and coroutine.wrap.

Tag rel-20140508 (3e322160ea3b0e2b4e7d5c188ec7cd869b0d338e).


Add fast metatable checking to sockets module, to match controller and condition variable module implementations. The speed gain in validating userdata objects is only approximately 30%, so it's probably not worth it to add this to any more modules as the absolute cost is miniscule and they're not called as heavily.

Add .type routine to controller, socket, thread, condition variable, signal listener, file notification, and dns modules.

Make sure all our pollable objects have three :pollfd, :events, and :timeout methods.

Allow :pollfd to return a condition variable, allowing user objects to mimic other pollable objects.


Don't return to buffered I/O callers an EPIPE received on input channel. That behavior snuck in after various changes to error and flow-control handling.

Make thrown socket errors include a description of the socket's peer name.


Add timeout capability to all buffered I/O routines through :settimeout. Buffered I/O errors are not preserved across calls until explicitly cleared with :clearerr, to prevent unsuspecting code dropping data on transient errors, particularly timeout errors. The behavior of :starttls had to change for the sake of consistency. It will now poll until completion, rather than return immediately.


Add fast metatable checking to the controller code, and short circuit on socket objects by calling straight into the socket library C code for the polling parameters.


Add chat server example.


Add :peereid and :peerpid socket methods.

Fix endless loop bug when an AF_UNIX socket could not be bound. The failure path depended on the SO_S_GETADDR iterator state to try another socket name or return the error. But the SO_S_GETADDR iterator state isn't used for AF_UNIX sockets.

Fix linking on various platforms after we required dlopen/dlsym in the threading module.

Add socket:listen wrapper to simplify error detection on listening sockets.

Silence some obnoxious compiler warnings on Linux and Solaris. They were totally bogus, but I finally relented because of the noise.

Tag rel-20140328 (52aec6d478cced10669254d90b6813a4c60ad602).


Remove openssl module documention and move to dedicated user guide under luaossl project.

Add Lua 5.3 support.

Tag rel-20140322 (bd7b727a9a212d8582af0bc9fce413285da7ebaf).


Add condition variable module, allowing light-weight user-defined events.

Add socket:connect wrapper to simplify explicit connect-phase timeout management.


Support primitve types other than LUA_TSTRING when passing arguments to a new thread.


Install OpenSSL mutexes when loading thread module.

Tag rel-20140130 (2d1f959d2c4ef82f4d0dcddd5812ed3803707648).


Fix slurp mode, which only slurped until the input bufsiz was filled. It resulted in a spurious EFAULT error being thrown (the default if errno == 0), because the code behaved as if something failed.

Fix socket.connect documentation to match the actual code.


Add openssl.rand.uniform() for generating cryptographically strong, uniform random integers in the interval [0, N-1]. The maximum interval is [0, 2^64-1], although for Lua 5.1 and 5.2 you're restricted to the integral range of your Lua VM number type, which is too narrow in most implementations. Lua 5.3 is expected to add a 64-bit integer type.


Obey SOCK_DGRAM semantics in input buffering code. Output buffering should work without changes, provided the output modes are sane—no buffering, line buffering, or explicit flushing when fully buffered.

Implement the "*a" slurp operation. Reads to EOF on SOCK_STREAM sockets, or the next message for SOCK_DGRAM.

Add openssl.rand module, with bindings to OpenSSL RAND_bytes and RAND_status.

Add :setbufsiz and :setmaxline methods, so applications can manipulate the internal soft buffer sizes and hard line limits.

Add :errors iterator method on cqueues object, so looping over continuation errors is made easier. Also add :loop method, to make it easier for constructs which only want to loop until an error is encountered.


Fix module preloading from threads to use loadstring on Lua 5.1/LuaJIT. Fix bug which cleared the O_NONBLOCK flag on pipe descriptors used for thread joining.


Refactored build system to be non-recursive, and to use new luapath script, enabling simultaneous builds of both Lua 5.1 and Lua 5.2 modules in a single invocation. I needed this for work, plus it makes development much easier.


Fixed bug in digest and HMAC modules which left the last argument to :update unprocessed.

Added openssl.cipher module, which binds OpenSSL EVP_CIPHER_CTX objects.

Moved the build to GNUmakefile. Now Makefile is a POSIX compatible stub using the special .DEFAULT target to forward to an invocation of gmake. This allows simply invoking make(1) on all supported platforms, presuming gmake is also installed.


Fixed bug in *h and *H read modes.

Added example HTTP daemon.


Added helper script to derive Lua compilation and installation paths. Simply passing prefix="..." to make should find the proper headers, even if multiple versions are installed, and select the proper installation paths. luainclude, luapath, luacpath, and LUAC can still be explicitly specified.


Changed the Make variables lua52include, lua52path, and lua52cpath to just luainclude, luapath, and luacpath.


Added openssl.pubkey:sign and openssl.pubkey:verify, which bind OpenSSL EVP_SignFinal and EVP_VerifyFinal. This allows constructing ad hoc signature schemes in applications.


Added openssl.digest and openssl.hmac modules.


Wrap dns_res_stat as resolver:stat, which returns a table of transmission statistics.

Tag rel-20130129 (65e4bf06b2d97741043dd52f5ad691014c67e7a9).


Added Makefile.debian, which was mistakenly left out of the tree previously.


Added Debian dpkg build. make -f Makefile.debian will build a lua-cqueues module.


Added and documented new bindings for SSL connection instances, including a new socket:checktls() method.


Added and documented DNS bindings.

Fixed OpenBSD build.


Documented OpenSSL bindings in PDF user guide.


Fixed LuaJIT compilation. No guarantees it won't break, however. Certainly one must be careful not to hold an upvalue reference to a cqueue controller from a coroutine, otherwise neither will ever be collected. Use cqueues.running, instead, to get a reference to the running controller.


Added insanely comprehensive OpenSSL bindings in ext/, including Lua bindings for manipulating bignums, public keys, X.509 certificates (names, altnames, chains, stores, etc), and SSL_CTX objects.

These bindings are similar to a X.509 Perl XS module I wrote several years ago and used for a CA which dynamically issued certificates to clients on an encrypted multimedia streaming network. That Perl module was proprietary, unfortunately. But I like using Lua better, anyhow.


Added a title page and examples to user guide, and tidied up some of the sections.


Added file change notification module supporting all three kernel facilities—Linux inotify, BSD EVFILT_VNODE, and Solaris PORT_SOURCE_FILE.

Tag rel-20120924 (dc930e4b0408556601b1bf78a26213f6387fee8b).


NetBSD 5.1 also has a broken pselect—neither pending nor unblocked signals are delivered inside pselect—so use internal implementation.

Added thread.start and accompanying thread module. On FreeBSD and NetBSD, if using the lua command-line interpreter it must be linked with pthreads, otherwise thread.start will hang.


Added pselect for OpenBSD and Apple using sigpending to predict interrupts before the signal swap and kqueue EVFILT_SIGNAL to detect interrupts after the swap.


Added socket.connect{} and socket.listen{}, which allow passing socket options as well as specifying a UNIX domain socket path instead of host/port pair. See README for documentation.

Added socket:uncork, for disabling the TCP_NOPUSH or TCP_CORK option set in the connect options table.

Added socket:close, for explicit and immediate closure of socket resources.


Added *h and *H read modes for reading MIME headers. Returns nil when a compliant header—field name, optional blanks, and colon—cannot be scanned from the head of the buffer.


Added socket.onerror and socket:onerror, which allow specifying per-socket error handlers. The handler receives a tuple—self, method-string, error-integer. It should either return an error-integer or throw an error.

By default EPIPE and ETIMEDOUT are returned directly; everything else thrown. EAGAIN is only ever returned from the semi-private internal methods, which always return socket errors directly.

Error codes are now always returned as integer values, unless thrown as formatted exception strings. Previously, some were returned as strings.


Added socket.pack and socket.unpack, for buffered network byte order bit packing.


POSIX threading work is mostly done, except for some magic which will allow copying cqueues modules into the new Lua VM. This will allow creating and running threads while inside a chroot jail. Access to other Lua modules could then be arranged via IPC or some other mechanism, with at least cqueues and the standard Lua modules available for use.


Added descriptor passing with socket.sendmsg and socket.recvmsg. Both bypass normal buffering. sendmsg sends Lua files, cqueues sockets, or integer descriptors. recvmsg always returns a cqueues socket object.


Add cqueues.cancel and cqueue:cancel, which allow explicit removal of a descriptor from polling queues, in preparation for allowing explicit early closure of descriptors.

Add cqueues.running, which returns the top-most cqueue currently executing, if any. The second return value is a boolean, true only if the calling coroutine is the one which the cqueue resumed.

Add a new cqueues.signal module. Signal disposition can be manipulated with signal.ignore, signal.default, signal.discard, signal.block, and signal.unblock. Each takes a series of signal number parameters, e.g. signal.SIGTERM, signal.SIGHUP, etc.

Add support for BSD EVFILT_SIGNAL and Linux signalfd. To create a new signal listener, do local sl = signal.listen(signal.SIGTERM). To poll for a signal call sl:wait([timeout]), which returns the signal number, or nil on timeout.

Solaris has nothing comparable to EVFILT_SIGNAL or signalfd, so Solaris uses a small timeout. For immediate response to signals for simple process management, a simple pattern using the new cqueue:pause routine can be used. cqueue:pause is a wrapper around pselect, which allows atomically changing a signal mask when polling on a descriptor. See examples/signal.pause for an example of the pattern.

I elected not to implement any hacks to handle signal retrieval from the main loop. Most event loops set a global handler which writes to a global pipe. But cqueues is intended to be embeddable, and automatically mucking around with global process state is to be avoided.


Add socket.pair binding to the socketpair syscall. Takes one optional argument, either "stream" or "dgram". On success returns two socket objects bound to each other, otherwise returns two nils and an error number.

This is in preparation for adding proc.fork and thread.start. Each will return a socket object to use for IPC with the new process or thread. I will also need to add socket:sendmsg so descriptors can be sent, as well.


Merged SIGPIPE suppression and /etc/nsswitch.conf support into dns.c. The work was done in this tree, but see the dns.c project page for a description.

Tag rel-20120805 (6d673b77209e1a5e4b1d37c25ec8600e73e3af5c).


Fix Solaris port_getn usage bug triggered by signal interruption.


Change Solaris build to use native SunPro by default. Fix SunPro warnings about unsupported GCC attributes originally used just to silence GCC and (especially) clang warnings. SunPro seems to have a broken diagnostic pass confused by macroized calls, resulting in erroneous "argument mismatch" warnings.

NetBSD's kevent definition uses intptr_t instead of void * for the .udata member. Fix conversion warnings by casting to typeof(.udata).

Add cqueues.VERSION, cqueues.VENDOR, and cqueues.COMMIT to identify different library versions.

Tagged release rel-20120713 (99cae0d736239a910c1dfc901335a7cc5fcf7f3d).


Add yielding socket:accept() with socket:clients() iterator. Add example script, echo.srv, to show usage.

Add cqueues.monotime, which returns the system's monotonic clock time.

Unbreak FreeBSD after fixing Solaris byte order issue in dns.h. FreeBSD also defines _BIG_ENDIAN, but the semantics are like BYTE_ORDER/BIG_ENDIAN, not the boolean behavior on Solaris.

Use esyscmd when generating errno table because NetBSD's M4 implementation had flushing issues and divert/undivert wouldn't work to solve it. Solaris lacks esyscmd, so stick with syscmd, which didn't exhibit flushing issues.

Tagged release rel-20120712 (b8deeb0e663d163d567c24adb5fd1291e1b6e8ae).

At this time, rel-20120712 is known to build and run on NetBSD 5.1, FreeBSD 9.0, Ubuntu Linux 12.04, Solaris 11, OS X 10.7.4, and OpenBSD 5.1.


Tagged release rel-20120711 (e0f6fbbb05cb7aa5d95becd6251417155987205e).


Tagged release rel-20120710.


Copyright (c) 2012-2017 William Ahern
Copyright (c) 2014-2017 Daurnimator

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.



git clone

Or visit the GitHub mirror















other projects

airctl | bsdauth | cnippets | libarena | libevnet | authldap | streamlocal | libnostd | zoned | dns.c | delegate.c | llrb.h | lpegk | json.c | cqueues | siphash.h | hexdump.c | timeout.c | luapath | luaossl | lunix | phf | runlua | autoguess | tarsum | prosody-openbsd | AnonNet