PageRenderTime 63ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/chapter2.txt

https://github.com/tsellon/zguide
Plain Text | 1518 lines | 1101 code | 417 blank | 0 comment | 0 complexity | 6b59a7cb96e60446d7a907be5898c4a3 MD5 | raw file
  1. .output chapter2.wd
  2. ++ Chapter Two - Intermediate Stuff
  3. In Chapter One we took 0MQ for a drive, with some basic examples of the main 0MQ patterns: request-reply, publish-subscribe, and pipeline. In this chapter we're going to get our hands dirty and start to learn how to use these tools in real programs.
  4. We'll cover:
  5. * How to create and work with 0MQ sockets.
  6. * How to send and receive messages on sockets.
  7. * How to build your apps around 0MQ's asynchronous I/O model.
  8. * How to handle multiple sockets in one thread.
  9. * How to handle fatal and non-fatal errors properly.
  10. * How to handle interrupt signals like Ctrl-C.
  11. * How to shutdown a 0MQ application cleanly.
  12. * How to check a 0MQ application for memory leaks.
  13. * How to send and receive multipart messages.
  14. * How to forward messages across networks.
  15. * How to build a simple message queuing broker.
  16. * How to write multithreaded applications with 0MQ.
  17. * How to use 0MQ to signal between threads.
  18. * How to use 0MQ to coordinate a network of nodes.
  19. * How to create durable sockets using socket identities.
  20. * How to create and use message envelopes for publish-subscribe.
  21. * How to do make durable subscribers that can recover from crashes.
  22. * Using the high-water mark (HWM) to protect against memory overflows.
  23. +++ The Zen of Zero
  24. The Ø in 0MQ is all about tradeoffs. On the one hand this strange name lowers 0MQ's visibility on Google and Twitter. On the other hand it annoys the heck out of some Danish folk who write us things like "ØMG røtfl", and "//Ø is not a funny looking zero!//" and "//Rødgrød med Fløde!//", which is apparently an insult that means "may your neighbours be the direct descendents of Grendel!" Seems like a fair trade.
  25. Originally the zero in 0MQ was meant as "zero broker" and (as close to) "zero latency" (as possible). In the meantime it has come to cover different goals: zero administration, zero cost, zero waste. More generally, "zero" refers to the culture of minimalism that permeates the project. We add power by removing complexity rather than exposing new functionality.
  26. +++ The Socket API
  27. To be perfectly honest, 0MQ does a kind of switch-and-bait on you. Which we don't apologize for, it's for your own good and hurts us more than it hurts you. It presents a familiar BSD socket API but that hides a bunch of message-processing machines that will slowly fix your world-view about how to design and write distributed software.
  28. Sockets are the de-facto standard API for network programming, as well as being useful for stopping your eyes from falling onto your cheeks. One thing that makes 0MQ especially tasty to developers is that it uses a standard socket API. Kudos to Martin Sustrik for pulling this idea off. It turns "Message Oriented Middleware", a phrase guaranteed to send the whole room off to Catatonia, into "Extra Spicy Sockets!" which leaves us with a strange craving for pizza, and a desire to know more.
  29. Like a nice pepperoni pizza, 0MQ sockets are easy to digest. Sockets have a life in four parts, just like BSD sockets:
  30. * Creating and destroying sockets, which go together to form a karmic circle of socket life (see zmq_socket[3], zmq_close[3]).
  31. * Configuring sockets by setting options on them and checking them if necessary (see zmq_setsockopt[3], zmq_getsockopt[3]).
  32. * Plugging sockets onto the network topology by creating 0MQ connections to and from them (see zmq_bind[3], zmq_connect[3]).
  33. * Using the sockets to carry data by writing and receiving messages on them (see zmq_send[3], zmq_recv[3]).
  34. Which looks like this, in C:
  35. [[code language="C"]]
  36. void *mousetrap;
  37. // Create socket for catching mice
  38. mousetrap = zmq_socket (context, ZMQ_PULL);
  39. // Configure the socket
  40. int64_t jawsize = 10000;
  41. zmq_setsockopt (mousetrap, ZMQ_HWM, &jawsize, sizeof jawsize);
  42. // Plug socket into mouse hole
  43. zmq_connect (mousetrap, "tcp://192.168.55.221:5001");
  44. // Wait for juicy mouse to arrive
  45. zmq_msg_t mouse;
  46. zmq_msg_init (&mouse);
  47. zmq_recv (mousetrap, &mouse, 0);
  48. // Destroy the mouse
  49. zmq_msg_close (&mouse);
  50. // Destroy the socket
  51. zmq_close (mousetrap);
  52. [[/code]]
  53. Note that sockets are always void pointers, and messages (which we'll come to very soon) are structures. So in C you pass sockets as-such, but you pass addresses of messages in all functions that work with messages, like zmq_send[3] and zmq_recv[3]. As a mnemonic, realize that "in 0MQ all ur sockets are belong to us", but messages are things you actually own in your code.
  54. Creating, destroying, and configuring sockets works as you'd expect for any object. But remember that 0MQ is an asynchronous, elastic fabric. This has some impact on how we plug sockets into the network topology, and how we use the sockets after that.
  55. +++ Plugging Sockets Into the Topology
  56. To create a connection between two nodes you use zmq_bind[3] in one node, and zmq_connect[3] in the other. As a general rule of thumb, the node which does zmq_bind[3] is a "server", sitting on a well-known network address, and the node which does zmq_connect[3] is a "client", with unknown or arbitrary network addresses. Thus we say that we "bind a socket to an endpoint" and "connect a socket to an endpoint", the endpoint being that well-known network address.
  57. 0MQ connections are somewhat different from old-fashioned TCP connections. The main notable differences are:
  58. * They go across an arbitrary transport ({{inproc}}, {{ipc}}, {{tcp}}, {{pgm}} or {{epgm}}). See zmq_inproc[7], zmq_ipc[7], zmq_tcp[7], zmq_pgm[7], and zmq_epgm[7].
  59. * They exist when a client does zmq_connect[3] to an endpoint, whether or not a server has already done zmq_bind[3] to that endpoint.
  60. * They are asynchronous, and have queues that magically exist where and when needed.
  61. * They may express a certain "messaging pattern", according to the type of socket used at each end.
  62. * One socket may have many outgoing and many incoming connections.
  63. * There is no zmq_accept() method. When a socket is bound to an endpoint it automatically starts accepting connections.
  64. * Your application code cannot work with these connections directly; they are encapsulated under the socket.
  65. Many architectures follow some kind of client-server model, where the server is the component that is most stable, and the clients are the components that are most dynamic, i.e. they come and go the most. There are sometimes issues of addressing: servers will be visible to clients, but not necessarily vice-versa. So mostly it's obvious which node should be doing zmq_bind[3] (the server) and which should be doing zmq_connect[3] (the client). It also depends on the kind of sockets you're using, with some exceptions for unusual network architectures. We'll look at socket types later.
  66. Now, imagine we start the client //before// we start the server. In traditional networking we get a big red Fail flag. But 0MQ lets us start and stop pieces arbitrarily. As soon as the client node does zmq_connect[3] the connection exists and that node can start to write messages to the socket. At some stage (hopefully before messages queue up so much that they start to get discarded, or the client blocks), the server comes alive, does a zmq_bind[3] and 0MQ starts to deliver messages.
  67. A server node can bind to many endpoints and it can do this using a single socket. This means it will accept connections across different transports:
  68. [[code language="C"]]
  69. zmq_bind (socket, "tcp://*:5555");
  70. zmq_bind (socket, "tcp://*:9999");
  71. zmq_bind (socket, "ipc://myserver.ipc");
  72. [[/code]]
  73. You cannot bind to the same endpoint twice, that will cause an exception.
  74. Each time a client node does a zmq_connect[3] to any of these endpoints, the server node's socket gets another connection. There is no inherent limit to how many connections a socket can have. A client node can also connect to many endpoints using a single socket.
  75. In most cases, which node acts as client, and which as server, is about network topology rather than message flow. However, there //are// cases (resending when connections are broken) where the same socket type will behave differently if it's a server or if it's a client.
  76. What this means is that you should always think in terms of "servers" as stable parts of your topology, with more-or-less fixed endpoint addresses, and "clients" as dynamic parts that come and go. Then, design your application around this model. The chances that it will "just work" are much better like that.
  77. Sockets have types. The socket type defines the semantics of the socket, its policies for routing messages inwards and outwards, queueing, etc. You can connect certain types of socket together, e.g. a publisher socket and a subscriber socket. Sockets work together in "messaging patterns". We'll look at this in more detail later.
  78. It's the ability to connect sockets in these different ways that gives 0MQ its basic power as a message queuing system. There are layers on top of this, such as devices and topic routing, which we'll get to later. But essentially, with 0MQ you define your network architecture by plugging pieces together like a child's construction toy.
  79. +++ Using Sockets to Carry Data
  80. To send and receive messages you use the zmq_send[3] and zmq_recv[3] methods. The names are conventional but 0MQ's I/O model is different enough from TCP's model that you will need time to get your head around it.
  81. [[code type="textdiagram"]]
  82. +------------+
  83. | |
  84. | Node |
  85. | |
  86. +------------+
  87. | Socket |
  88. \------------/
  89. ^
  90. |
  91. 1 to 1
  92. |
  93. v
  94. /------------\
  95. | Socket |
  96. +------------+
  97. | |
  98. | Node |
  99. | |
  100. +------------+
  101. Figure # - TCP sockets are 1 to 1
  102. [[/code]]
  103. Let's look at the main differences between TCP sockets and 0MQ sockets when it comes to carrying data:
  104. * 0MQ sockets carry messages, rather than bytes (as in TCP) or frames (as in UDP). A message is a length-specified blob of binary data. We'll come to messages shortly, their design is optimized for performance and thus somewhat tricky to understand.
  105. * 0MQ sockets do their I/O in a background thread. This means that messages arrive in a local input queue, and are sent from a local output queue, no matter what your application is busy doing. These are configurable memory queues, by the way.
  106. * 0MQ sockets can, depending on the socket type, be connected to (or from, it's the same) many other sockets. Where TCP emulates a one-to-one phone call, 0MQ implements one-to-many (like a radio broadcast), many-to-many (like a post office), many-to-one (like a mail box), and even one-to-one.
  107. * 0MQ sockets can send to many endpoints (creating a fan-out model), or receive from many endpoints (creating a fan-in model).
  108. [[code type="textdiagram"]]
  109. +------------+ +------------+
  110. | | | |
  111. | Node | | Node |
  112. | | | |
  113. +------------+ +------------+
  114. | Socket | | Socket |
  115. \----+-+-----/ \------+-----/
  116. | | :
  117. 1 to N | +------------------------+
  118. Fan out | |
  119. +------------------------+ | N to 1
  120. | | | Fan in
  121. v v v
  122. /------------\ /------------\
  123. | Socket | | Socket |
  124. +------------+ +------------+
  125. | | | |
  126. | Node | | Node |
  127. | | | |
  128. +------------+ +------------+
  129. Figure # - 0MQ sockets are N to N
  130. [[/code]]
  131. So writing a message to a socket may send the message to one or many other places at once, and conversely, one socket will collect messages from all connections sending messages to it. The zmq_recv[3] method uses a fair-queuing algorithm so each sender gets an even chance.
  132. The zmq_send[3] method does not actually send the message to the socket connection(s). It queues the message so that the I/O thread can send it asynchronously. It does not block except in some exception cases. So the message is not necessarily sent when zmq_send[3] returns to your application. If you created a message using zmq_msg_init_data[3] you cannot reuse the data or free it, otherwise the I/O thread will rapidly find itself writing overwritten or unallocated garbage. This is a common mistake for beginners. We'll see a little later how to properly work with messages.
  133. +++ Unicast Transports
  134. 0MQ provides a set of unicast transports ({{inproc}}, {{ipc}}, and {{tcp}}) and multicast transports (epgm, pgm). Multicast is an advanced technique that we'll come to later. Don't even start using it unless you know that your fanout ratios will make 1-to-N unicast impossible.
  135. For most common cases, use **{{tcp}}**, which is a //disconnected TCP// transport. It is elastic, portable, and fast enough for most cases. We call this 'disconnected' because 0MQ's {{tcp}} transport doesn't require that the endpoint exists before you connect to it. Clients and servers can connect and bind at any time, can go and come back, and it remains transparent to applications.
  136. The inter-process transport, **{{ipc}}**, is like {{tcp}} except that it is abstracted from the LAN, so you don't need to specify IP addresses or domain names. This makes it better for some purposes, and we use it quite often in the examples in this book. 0MQ's {{ipc}} transport is disconnected, like {{tcp}}. It has one limitation: it does not work on Windows. This may be fixed in future versions of 0MQ. By convention we use endpoint names with an ".ipc" extension to avoid potential conflict with other file names. On UNIX systems, if you use {{ipc}} endpoints you need to create these with appropriate permissions otherwise they may not be shareable between processes running under different user ids. You must also make sure all processes can access the files, e.g. by running in the same working directory.
  137. The inter-thread transport, **{{inproc}}**, is a connected signaling transport. It is much faster than {{tcp}} or {{ipc}}. This transport has a specific limitation compared to {{ipc}} and {{tcp}}: **you must do bind before connect**. This is something future versions of 0MQ may fix, but at present this defines you use {{inproc}} sockets. We create and bind one socket, start the child threads, which create and connect the other sockets.
  138. +++ 0MQ is Not a Neutral Carrier
  139. A common question that newcomers to 0MQ ask (it's one I asked myself) is something like, "//how do I write a XYZ server in 0MQ?//" For example, "how do I write an HTTP server in 0MQ?"
  140. The implication is that if we use normal sockets to carry HTTP requests and responses, we should be able to use 0MQ sockets to do the same, only much faster and better.
  141. Sadly the answer is "this is not how it works". 0MQ is not a neutral carrier, it imposes a framing on the transport protocols it uses. This framing is not compatible with existing protocols, which tend to use their own framing. For example, here is an HTTP request, and a 0MQ request, both over TCP/IP:
  142. [[code type="textdiagram"]]
  143. +----------------+----+----+----+----+
  144. | GET /index.html| 13 | 10 | 13 | 10 |
  145. +----------------+----+----+----+----+
  146. Figure # - HTTP request
  147. [[/code]]
  148. Where the HTTP request uses CR-LF as its simplest framing delimiter, and 0MQ uses a length-specified frame:
  149. [[code type="textdiagram"]]
  150. +---+---+---+---+---+---+
  151. | 5 | H | E | L | L | O |
  152. +---+---+---+---+---+---+
  153. Figure # - 0MQ request
  154. [[/code]]
  155. So you could write a HTTP-like protocol using 0MQ, using for example the request-reply socket pattern. But it would not be HTTP.
  156. There is however a good answer to the question, "how can I make profitable use of 0MQ when making my new XYZ server?" You need to implement whatever protocol you want to speak in any case, but you can connect that protocol server (which can be extremely thin) to a 0MQ backend that does the real work. The beautiful part here is that you can then extend your backend with code in any language, running locally or remotely, as you wish. Zed Shaw's [http://www.mongrel2.org Mongrel2] web server is a great example of such an architecture.
  157. +++ I/O Threads
  158. We said that 0MQ does I/O in a background thread. One I/O thread (for all sockets) is sufficient for all but the most extreme applications. This is the magic '1' that we use when creating a context, meaning "use one I/O thread":
  159. [[code language="C"]]
  160. void *context = zmq_init (1);
  161. [[/code]]
  162. There is a major difference between a 0MQ application and a conventional networked application, which is that you don't create one socket per connection. One socket handles all incoming and outcoming connections for a particular point of work. E.g. when you publish to a thousand subscribers, it's via one socket. When you distribute work among twenty services, it's via one socket. When you collect data from a thousand web applications, it's via one socket.
  163. This has a fundamental impact on how you write applications. A traditional networked application has one process or one thread per remote connection, and that process or thread handles one socket. 0MQ lets you collapse this entire structure into a single thread, and then break it up as necessary for scaling.
  164. +++ Core Messaging Patterns
  165. Underneath the brown paper wrapping of 0MQ's socket API lies the world of messaging patterns. If you have a background in enterprise messaging, these will be vaguely familiar. But to most 0MQ newcomers they are a surprise, we're so used to the TCP paradigm where a socket represents another node.
  166. Let's recap briefly what 0MQ does for you. It delivers blobs of data (messages) to nodes, quickly and efficiently. You can map nodes to threads, processes, or boxes. It gives your applications a single socket API to work with, no matter what the actual transport (like in-process, inter-process, TCP, or multicast). It automatically reconnects to peers as they come and go. It queues messages at both sender and receiver, as needed. It manages these queues carefully to ensure processes don't run out of memory, overflowing to disk when appropriate. It handles socket errors. It does all I/O in background threads. It uses lock-free techniques for talking between nodes, so there are never locks, waits, semaphores, or deadlocks.
  167. But cutting through that, it routes and queues messages according to precise recipes called //patterns//. It is these patterns that provide 0MQ's intelligence. They encapsulate our hard-earned experience of the best ways to distribute data and work. 0MQ's patterns are hard-coded but future versions may allow user-definable patterns.
  168. 0MQ patterns are implemented by pairs of sockets with matching types. In other words, to understand 0MQ patterns you need to understand socket types and how they work together. Mostly this just takes learning, there is little that is obvious at this level.
  169. The built-in core 0MQ patterns are:
  170. * **Request-reply**, which connects a set of clients to a set of services. This is a remote procedure call and task distribution pattern.
  171. * **Publish-subscribe**, which connects a set of publishers to a set of subscribers. This is a data distribution pattern.
  172. * **Pipeline**, connects nodes in a fan-out / fan-in pattern that can have multiple steps, and loops. This is a parallel task distribution and collection pattern.
  173. We looked at each of these in the first chapter. There's one more pattern that people tend to try to use when they still think of 0MQ in terms of traditional TCP sockets:
  174. * **Exclusive pair**, which connects two sockets in an exclusive pair. This is a low-level pattern for specific, advanced use-cases. We'll see an example at the end of this chapter.
  175. The zmq_socket[3] man page is fairly clear about the patterns, it's worth reading several times until it starts to make sense. We'll look at each pattern and the use-cases it covers.
  176. These are the socket combinations that are valid for a connect-bind pair (either side can bind):
  177. * PUB and SUB
  178. * REQ and REP
  179. * REQ and ROUTER
  180. * DEALER and REP
  181. * DEALER and ROUTER
  182. * DEALER and DEALER
  183. * ROUTER and ROUTER
  184. * PUSH and PULL
  185. * PAIR and PAIR
  186. Any other combination will produce undocumented and unreliable results and future versions of 0MQ will probably return errors if you try them. You can and will of course bridge other socket types //via code//, i.e. read from one socket type and write to another.
  187. +++ High-level Messaging Patterns
  188. These four core patterns are cooked-in to 0MQ. They are part of the 0MQ API, implemented in the core C++ library, and guaranteed to be available in all fine retail stores. If one day the Linux kernel includes 0MQ, for example, these patterns would be there.
  189. On top, we add //high-level patterns//. We build these high-level patterns on top of 0MQ and implement them in whatever language we're using for our application. They are not part of the core library, do not come with the 0MQ package, and exist in their own space, as part of the 0MQ community.
  190. One of the things we aim to provide you with this guide are a set of such high-level patterns, both small (how to handle messages sanely) to large (how to make a reliable publish-subscribe architecture).
  191. +++ Working with Messages
  192. On the wire, 0MQ messages are blobs of any size from zero upwards, fitting in memory. You do your own serialization using Google Protocol Buffers, XDR, JSON, or whatever else your applications need to speak. It's wise to choose a data representation that is portable and fast, but you can make your own decisions about trade-offs.
  193. In memory, 0MQ messages are zmq_msg_t structures (or classes depending on your language). Here are the basic ground rules for using 0MQ messages in C:
  194. * You create and pass around zmq_msg_t objects, not blocks of data.
  195. * To read a message you use zmq_msg_init[3] to create an empty message, and then you pass that to zmq_recv[3].
  196. * To write a message from new data, you use zmq_msg_init_size[3] to create a message and at the same time allocate a block of data of some size. You then fill that data using memcpy, and pass the message to zmq_send[3].
  197. * To release (not destroy) a message you call zmq_msg_close[3]. This drops a reference, and eventually 0MQ will destroy the message.
  198. * To access the message content you use zmq_msg_data[3]. To know how much data the message contains, use zmq_msg_size[3].
  199. * Do not use zmq_msg_move[3], zmq_msg_copy[3], or zmq_msg_init_data[3] unless you read the man pages and know precisely why you need these.
  200. Here is a typical chunk of code working with messages, which should be familiar if you have been paying attention. This is from the zhelpers.h file we use in all the examples:
  201. [[code language="C"]]
  202. // Receive 0MQ string from socket and convert into C string
  203. static char *
  204. s_recv (void *socket) {
  205. zmq_msg_t message;
  206. zmq_msg_init (&message);
  207. zmq_recv (socket, &message, 0);
  208. int size = zmq_msg_size (&message);
  209. char *string = malloc (size + 1);
  210. memcpy (string, zmq_msg_data (&message), size);
  211. zmq_msg_close (&message);
  212. string [size] = 0;
  213. return (string);
  214. }
  215. // Convert C string to 0MQ string and send to socket
  216. static int
  217. s_send (void *socket, char *string) {
  218. int rc;
  219. zmq_msg_t message;
  220. zmq_msg_init_size (&message, strlen (string));
  221. memcpy (zmq_msg_data (&message), string, strlen (string));
  222. rc = zmq_send (socket, &message, 0);
  223. assert (!rc);
  224. zmq_msg_close (&message);
  225. return (rc);
  226. }
  227. [[/code]]
  228. You can easily extend this code to send and receive blobs of arbitrary length.
  229. **Note than when you have passed a message to zmq_send(3), ØMQ will clear the message, i.e. set the size to zero. You cannot send the same message twice, and you cannot access the message data after sending it.**
  230. If you want to send the same message more than once, create a second message, initialize it using zmq_msg_init[3] and then use zmq_msg_copy[3] to create a copy of the first message. This does not copy the data but the reference. You can then send the message twice (or more, if you create more copies) and the message will only be finally destroyed when the last copy is sent or closed.
  231. 0MQ also supports //multipart// messages, which let you handle a list of blobs as a single message. This is widely used in real applications and we'll look at that later in this chapter and in Chapter Three.
  232. Some other things that are worth knowing about messages:
  233. * 0MQ sends and receives them atomically, i.e. you get a whole message, or you don't get it at all.
  234. * 0MQ does not send a message right away but at some indeterminate later time.
  235. * You can send zero-length messages, e.g. for sending a signal from one thread to another.
  236. * A message must fit in memory. If you want to send files of arbitrary sizes, you should break them into pieces and send each piece as a separate message.
  237. * You must call zmq_msg_close[3] when finished with a message, in languages that don't automatically destroy objects when a scope closes.
  238. And to be necessarily repetitive, do not use zmq_msg_init_data[3], yet. This is a zero-copy method and guaranteed to create trouble for you. There are far more important things to learn about 0MQ before you start to worry about shaving off microseconds.
  239. +++ Handling Multiple Sockets
  240. In all the examples so far, the main loop of most examples has been:
  241. # wait for message on socket
  242. # process message
  243. # repeat
  244. What if we want to read from multiple sockets at the same time? The simplest way is to connect one socket to multiple endpoints and get 0MQ to do the fanin for us. This is legal if the remote endpoints are in the same pattern but it would be illegal to e.g. connect a PULL socket to a PUB endpoint. Fun, but illegal. If you start mixing patterns you break future scalability.
  245. The right way is to use zmq_poll[3]. An even better way might be to wrap zmq_poll[3] in a framework that turns it into a nice event-driven //reactor//, but it's significantly more work than we want to cover here.
  246. Let's start with a dirty hack, partly for the fun of not doing it right, but mainly because it lets me show you how to do non-blocking socket reads. Here is a simple example of reading from two sockets using non-blocking reads. This rather confused program acts both as a subscriber to weather updates, and a worker for parallel tasks:
  247. [[code type="example" title="Multiple socket reader" name="msreader"]]
  248. [[/code]]
  249. The cost of this approach is some additional latency on the first message (the sleep at the end of the loop, when there are no waiting messages to process). This would be a problem in applications where sub-millisecond latency was vital. Also, you need to check the documentation for nanosleep() or whatever function you use to make sure it does not busy-loop.
  250. You can treat the sockets fairly by reading first from one, then the second rather than prioritizing them as we did in this example. This is called "fair-queuing", something that 0MQ does automatically when one socket receives messages from more than one source.
  251. Now let's see the same little senseless application done right, using zmq_poll[3]:
  252. [[code type="example" title="Multiple socket poller" name="mspoller"]]
  253. [[/code]]
  254. +++ Handling Errors and ETERM
  255. 0MQ's error handling philosophy is a mix of fail-fast and resilience. Processes, we believe, should be as vulnerable as possible to internal errors, and as robust as possible against external attacks and errors. To give an analogy, a living cell will self-destruct if it detects a single internal error, yet it will resist attack from the outside by all means possible. Assertions, which pepper the 0MQ code, are absolutely vital to robust code, they just have to be on the right side of the cellular wall. And there should be such a wall. If it is unclear whether a fault is internal or external, that is a design flaw that needs to be fixed.
  256. In C, assertions stop the application immediately with an error. In other languages you may get exceptions or halts.
  257. When 0MQ detects an external fault it returns an error to the calling code. In some rare cases it drops messages silently, if there is no obvious strategy for recovering from the error. In a few places 0MQ still asserts on external faults, but these are considered bugs.
  258. In most of the C examples we've seen so far there's been no error handling. **Real code should do error handling on every single 0MQ call**. If you're using a language binding other than C, the binding may handle errors for you. In C you do need to do this yourself. There are some simple rules, starting with POSIX conventions:
  259. * Methods that create objects will return NULL in case they fail.
  260. * Other methods will return 0 on success and other values (mostly -1) on an exceptional condition (usually failure).
  261. * The error code is provided in {{errno}} or zmq_errno[3].
  262. * A descriptive error text for logging is provided by zmq_strerror[3].
  263. There are two main exceptional conditions that you may want to handle as non-fatal:
  264. * When a thread calls zmq_recv[3] with the NOBLOCK option and there is no waiting data. 0MQ will return -1 and set errno to EAGAIN.
  265. * When a thread calls zmq_term[3] and other threads are doing blocking work. The zmq_term[3] call closes the context and all blocking calls exit with -1, and errno set to ETERM.
  266. What this boils down to is that in most cases you can use assertions on 0MQ calls, like this, in C:
  267. [[code language="C"]]
  268. void *context = zmq_init (1);
  269. assert (context);
  270. void *socket = zmq_socket (context, ZMQ_REP);
  271. assert (socket);
  272. int rc;
  273. rc = zmq_bind (socket, "tcp://*:5555");
  274. assert (rc == 0);
  275. [[/code]]
  276. In the first version of this code I put the assert() call around the function. Not a good idea, since an optimized build will turn all assert() macros to null and happily wallop those functions. Use a return code, and assert the return code.
  277. Let's see how to shut down a process cleanly. We'll take the parallel pipeline example from the previous section. If we've started a whole lot of workers in the background, we now want to kill them when the batch is finished. Let's do this by sending a kill message to the workers. The best place to do this is the sink, since it really knows when the batch is done.
  278. How do we connect the sink to the workers? The PUSH/PULL sockets are one-way only. The standard 0MQ answer is: create a new socket flow for each type of problem you need to solve. We'll use a publish-subscribe model to send kill messages to the workers:
  279. * The sink creates a PUB socket on a new endpoint.
  280. * Workers bind their input socket to this endpoint.
  281. * When the sink detects the end of the batch it sends a kill to its PUB socket.
  282. * When a worker detects this kill message, it exits.
  283. It doesn't take much new code in the sink:
  284. [[code language="C"]]
  285. void *control = zmq_socket (context, ZMQ_PUB);
  286. zmq_bind (control, "tcp://*:5559");
  287. ...
  288. // Send kill signal to workers
  289. zmq_msg_init_data (&message, "KILL", 5);
  290. zmq_send (control, &message, 0);
  291. zmq_msg_close (&message);
  292. [[/code]]
  293. [[code type="textdiagram"]]
  294. +-------------+
  295. | |
  296. | Ventilator |
  297. | |
  298. +-------------+
  299. | PUSH |
  300. \------+------/
  301. |
  302. tasks
  303. |
  304. +---------------+---------------+
  305. | | |
  306. | /=--------|-----+=--------|-----+------\
  307. task | task | task | :
  308. | | | | | | |
  309. v v v v v v |
  310. /------+-----\ /------+-----\ /------+-----\ |
  311. | PULL | SUB | | PULL | SUB | | PULL | SUB | |
  312. +------+-----+ +------+-----+ +------+-----+ |
  313. | | | | | | |
  314. | Worker | | Worker | | Worker | |
  315. | | | | | | |
  316. +------------+ +------------+ +------------+ |
  317. | PUSH | | PUSH | | PUSH | |
  318. \-----+------/ \-----+------/ \-----+------/ |
  319. | | | |
  320. result result result |
  321. | | | |
  322. +---------------+---------------+ |
  323. | |
  324. results |
  325. | |
  326. v |
  327. /-------------\ |
  328. | PULL | |
  329. +-------------+ |
  330. | | |
  331. | Sink | |
  332. | | |
  333. +-------------+ |
  334. | PUB | |
  335. \------+------/ |
  336. | |
  337. KILL signal |
  338. | |
  339. \--------------------------/
  340. Figure # - Parallel Pipeline with Kill signaling
  341. [[/code]]
  342. Here is the worker process, which manages two sockets (a PULL socket getting tasks, and a SUB socket getting control commands) using the zmq_poll[3] technique we saw earlier:
  343. [[code type="example" title="Parallel task worker with kill signaling" name="taskwork2"]]
  344. [[/code]]
  345. Here is the modified sink application. When it's finished collecting results it broadcasts a KILL message to all workers:
  346. [[code type="example" title="Parallel task sink with kill signaling" name="tasksink2"]]
  347. [[/code]]
  348. +++ Handling Interrupt Signals
  349. Realistic applications need to shutdown cleanly when interrupted with Ctrl-C or another signal such as SIGTERM. By default, these simply kill the process, meaning messages won't be flushed, files won't be closed cleanly, etc.
  350. Here is how we handle a signal in various languages:
  351. [[code type="example" title="Handling Ctrl-C cleanly" name="interrupt"]]
  352. [[/code]]
  353. The program provides s_catch_signals(), which traps Ctrl-C (SIGINT) and SIGTERM. When either of these signals arrive, the s_catch_signals() handler sets the global variable s_interrupted. Your application will not die automatically, you have to now explicitly check for an interrupt, and handle it properly. Here's how:
  354. * Call s_catch_signals() (copy this from interrupt.c) at the start of your main code. This sets-up the signal handling.
  355. * If your code is blocking in zmq_recv[3], zmq_poll[3], or zmq_send[3], when a signal arrives, the call will return with EINTR.
  356. * Wrappers like s_recv() return NULL if they are interrupted.
  357. * So, your application checks for an EINTR return code, a NULL return, and/or s_interrupted.
  358. Here is a typical code fragment:
  359. [[code]]
  360. s_catch_signals ();
  361. client = zmq_socket (...);
  362. while (!s_interrupted) {
  363. char *message = s_recv (client);
  364. if (!message)
  365. break; // Ctrl-C used
  366. }
  367. zmq_close (client);
  368. [[/code]]
  369. If you call s_catch_signals() and don't test for interrupts, the your application will become immune to Ctrl-C and SIGTERM, which may be useful, but is usually not.
  370. +++ Detecting Memory Leaks
  371. Any long-running application has to manage memory correctly, or eventually it'll use up all available memory and crash. If you use a language that handles this automatically for you, congratulations. If you program in C or C++ or any other language where you're responsible for memory management, here's a short tutorial on using valgrind, which among other things will report on any leaks your programs have.
  372. * To install valgrind, e.g. on Ubuntu or Debian: {{sudo apt-get install valgrind}}.
  373. * By default, 0MQ will cause valgrind to complain a lot. To remove these warnings, rebuild 0MQ with the ZMQ_MAKE_VALGRIND_HAPPY macro, thus:
  374. [[code]]
  375. $ cd zeromq2
  376. $ export CPPFLAGS=-DZMQ_MAKE_VALGRIND_HAPPY
  377. $ ./configure
  378. $ make clean; make
  379. $ sudo make install
  380. [[/code]]
  381. * Fix your applications to exit cleanly after Ctrl-C. For any application that exits by itself, that's not needed, but for long-running applications (like devices), this is essential, otherwise valgrind will complain about all currently allocated memory.
  382. * Build your application with -DDEBUG, if it's not your default setting. That ensures valgrind can tell you exactly where memory is being leaked.
  383. * Finally, run valgrind thus:
  384. [[code]]
  385. valgrind --tool=memcheck --leak-check=full someprog
  386. [[/code]]
  387. And after fixing any errors it reported, you should get the pleasant message:
  388. [[code]]
  389. ==30536== ERROR SUMMARY: 0 errors from 0 contexts...
  390. [[/code]]
  391. +++ Multipart Messages
  392. 0MQ lets us compose a message out of several frames, giving us a 'multipart message'. Realistic applications use multipart messages heavily, especially to make "envelopes". We'll look at them later. What we'll learn now is simply how to safely (but blindly) read and write multipart messages because otherwise the devices we write won't work with applications that use multipart messages.
  393. When you work with multipart messages, each part is a zmq_msg item. E.g. if you are sending a message with five parts, you must construct, send, and destroy five zmq_msg items. You can do this in advance (and store the zmq_msg items in an array or structure), or as you send them, one by one.
  394. Here is how we send the frames in a multipart message (we receive each frame into a message object):
  395. [[code language="C"]]
  396. zmq_send (socket, &message, ZMQ_SNDMORE);
  397. ...
  398. zmq_send (socket, &message, ZMQ_SNDMORE);
  399. ...
  400. zmq_send (socket, &message, 0);
  401. [[/code]]
  402. Here is how we receive and process all the parts in a message, be it single part or multipart:
  403. [[code language="C"]]
  404. while (1) {
  405. zmq_msg_t message;
  406. zmq_msg_init (&message);
  407. zmq_recv (socket, &message, 0);
  408. // Process the message part
  409. zmq_msg_close (&message);
  410. int64_t more;
  411. size_t more_size = sizeof (more);
  412. zmq_getsockopt (socket, ZMQ_RCVMORE, &more, &more_size);
  413. if (!more)
  414. break; // Last message part
  415. }
  416. [[/code]]
  417. Some things to know about multipart messages:
  418. * When you send a multipart message, the first part (and all following parts) are only sent when you send the final part.
  419. * If you are using zmq_poll[3], when you receive the first part of a message, all the rest has also arrived.
  420. * You will receive all parts of a message, or none at all.
  421. * Each part of a message is a separate zmq_msg item.
  422. * You will receive all parts of a message whether or not you check the RCVMORE option.
  423. * On sending, 0MQ queues message parts in memory until the last is received, then sends them all.
  424. * There is no way to cancel a partially sent message, except by closing the socket.
  425. +++ Intermediates and Devices
  426. Any connected set hits a complexity curve as the number of set members increases. A small number of members can all know about each other but as the set gets larger, the cost to each member of knowing all other interesting members grows linearly, and the overall cost of connecting members grows factorially. The solution is to break sets into smaller ones, and use intermediates to connect the sets.
  427. This pattern is extremely common in the real world and is why our societies and economies are filled with intermediaries who have no other real function than to reduce the complexity and scaling costs of larger networks. Intermediaries are typically called wholesalers, distributors, managers, etc.
  428. A 0MQ network like any cannot grow beyond a certain size without needing intermediaries. In 0MQ, we call these "devices". When we use 0MQ we usually start building our applications as a set of nodes on a network with the nodes talking to each other, without intermediaries:
  429. [[code type="textdiagram"]]
  430. +---------+
  431. | |
  432. | Node |
  433. | |
  434. +---------+
  435. | Socket |
  436. \----+----/
  437. |
  438. |
  439. +------+------+
  440. | |
  441. | |
  442. /----+----\ /----+----\
  443. | Socket | | Socket |
  444. +---------+ +---------+
  445. | | | |
  446. | Node | | Node |
  447. | | | |
  448. +---------+ +---------+
  449. Figure # - Small scale 0MQ application
  450. [[/code]]
  451. And then we extend the application across a wider network, placing devices in specific places and scaling up the number of nodes:
  452. [[code type="textdiagram"]]
  453. +---------+
  454. | |
  455. | Node |
  456. | |
  457. +---------+
  458. | Socket |
  459. \----+----/
  460. |
  461. |
  462. +-------------+-------------+
  463. | | |
  464. | | |
  465. /----+----\ /----+----\ /----+----\
  466. | Socket | | Socket | | Socket |
  467. +---------+ +---------+ +---------+
  468. | | | | | |
  469. | Node | | Node | | Device |
  470. | | | | | |
  471. +---------+ +---------+ +---------+
  472. | Socket |
  473. \----+----/
  474. |
  475. |
  476. +------+------+
  477. | |
  478. | |
  479. /----+----\ /----+----\
  480. | Socket | | Socket |
  481. +---------+ +---------+
  482. | | | |
  483. | Node | | Node |
  484. | | | |
  485. +---------+ +---------+
  486. Figure # - Larger scale 0MQ application
  487. [[/code]]
  488. 0MQ devices generally connect a set of 'frontend' sockets to a set of 'backend' sockets, though there are no strict design rules. They ideally run with no state, so that it becomes possible to stretch applications over as many intermediates as needed. You can run them as threads within a process, or as stand-alone processes. 0MQ provides some very basic devices but you will in practice develop your own.
  489. 0MQ devices can do intermediation of addresses, services, queues, or any other abstraction you care to define above the message and socket layers. Different messaging patterns have different complexity issues and need different kinds of intermediation. For example, request-reply works well with queue and service abstractions, while publish-subscribe works well with streams or topics.
  490. What's interesting about 0MQ as compared to traditional centralized brokers is that you can place devices precisely where you need them, and they can do the optimal intermediation.
  491. ++++ A Publish-Subscribe Proxy Server
  492. It is a common requirement to extend a publish-subscribe architecture over more than one network segment or transport. Perhaps there are a group of subscribers sitting at a remote location. Perhaps we want to publish to local subscribers via multicast, and to remote subscribers via TCP.
  493. We're going to write a simple proxy server that sits in between a publisher and a set of subscribers, bridging two networks. This is perhaps the simplest case of a useful device. The device has two sockets, a frontend facing the internal network, where the weather server is sitting, and a backend facing subscribers on the external network. It subscribes to the weather service on the frontend socket, and republishes its data on the backend socket:
  494. [[code type="example" title="Weather update proxy" name="wuproxy"]]
  495. [[/code]]
  496. We call this a //proxy// because it acts as a subscriber to publishers, and acts as a publisher to subscribers. That means you can slot this device into an existing network without affecting it (of course the new subscribers need to know to speak to the proxy).
  497. [[code type="textdiagram"]]
  498. +-----------+
  499. | |
  500. | Publisher |
  501. | |
  502. +-----------+
  503. | PUB |
  504. \-----------/
  505. bind
  506. tcp://192.168.55.210:5556
  507. |
  508. |
  509. +----------------+----------------+
  510. | | |
  511. | | |
  512. connect connect |
  513. /------------\ /------------\ connect
  514. | SUB | | SUB | /------------\
  515. +------------+ +------------+ | SUB |
  516. | | | | +------------+
  517. | Subscriber | | Subscriber | | |
  518. | | | | | Forwarder |
  519. +------------+ +------------+ | |
  520. +------------+
  521. Internal network | PUB |
  522. ---------------------------------\------------/--------
  523. External network bind
  524. tcp://10.1.1.0:8100
  525. |
  526. |
  527. +--------+--------+
  528. | |
  529. | |
  530. connect connect
  531. /------------\ /------------\
  532. | SUB | | SUB |
  533. +------------+ +------------+
  534. | | | |
  535. | Subscriber | | Subscriber |
  536. | | | |
  537. +------------+ +------------+
  538. Figure # - Forwarder proxy device
  539. [[/code]]
  540. Note that this application is multipart safe. It correctly detects multipart messages and sends them as it reads them. If we did not set the SNDMORE option on outgoing multipart data, the final recipient would get a corrupted message. You should always make your devices multipart safe so that there is no risk they will corrupt the data they switch.
  541. ++++ A Request-Reply Broker
  542. Let's explore how to solve a problem of scale by writing a little message queuing broker in 0MQ. We'll look at the request-reply pattern for this case.
  543. In the Hello World client-server application we have one client that talks to one service. However in real cases we usually need to allow multiple services as well as multiple clients. This lets us scale up the power of the service (many threads or processes or boxes rather than just one). The only constraint is that services must be stateless, all state being in the request or in some shared storage such as a database.
  544. There are two ways to connect multiple clients to multiple servers. The brute-force way is to connect each client socket to multiple service endpoints. One client socket can connect to multiple service sockets, and requests are load-balanced among these services. Let's say you connect a client socket to three service endpoints, A, B, and C. The client makes requests R1, R2, R3, R4. R1 and R4 go to service A, R2 goes to B, and R3 goes to service C.
  545. [[code type="textdiagram"]]
  546. +-----------+
  547. | |
  548. | Client |
  549. | |
  550. +-----------+
  551. | REQ |
  552. \-----+-----/
  553. |
  554. R1, R2, R3, R4
  555. |
  556. +-------------+-------------+
  557. | | |
  558. R1, R4 R2 R3
  559. | | |
  560. v v v
  561. /---------\ /---------\ /---------\
  562. | REP | | REP | | REP |
  563. +---------+ +---------+ +---------+
  564. | | | | | |
  565. | Service | | Service | | Service |
  566. | A | | B | | C |
  567. | | | | | |
  568. +---------+ +---------+ +---------+
  569. Figure # - Load balancing of requests
  570. [[/code]]
  571. This design lets you add more clients cheaply. You can also add more services. Each client will load-balance its requests to the services. But each client has to know the service topology. If you have 100 clients and then you decide to add three more services, you need to reconfigure and restart 100 clients in order for the clients to know about the three new services.
  572. That's clearly not the kind of thing we want to be doing at 3am when our supercomputing cluster has run out of resources and we desperately need to add a couple of hundred new service nodes. Too many stable pieces are like liquid concrete: knowledge is distributed and the more stable pieces you have, the more effort it is to change the topology. What we want is something sitting in between clients and services that centralizes all knowledge of the topology. Ideally, we should be able to add and remove services or clients at any time without touching any other part of the topology.
  573. So we'll write a little message queuing broker that gives us this flexibility. The broker binds to two endpoints, a frontend for clients and a backend for services. It then uses zmq_poll[3] to monitor these two sockets for activity and when it has some, it shuttles messages between its two sockets. It doesn't actually manage any queues explicitly -- 0MQ does that automatically on each socket.
  574. When you use REQ to talk to REP you get a strictly synchronous request-reply dialog. The client sends a request, the service reads the request and sends a reply. The client then reads the reply. If either the client or the service try to do anything else (e.g. sending two requests in a row without waiting for a response) they will get an error.
  575. But our broker has to be non-blocking. Obviously we can use zmq_poll[3] to wait for activity on either socket, but we can't use REP and REQ.
  576. Luckily there are two sockets called DEALER and ROUTER that let you do non-blocking request-response. These sockets used to be called XREQ and XREP, and you may see these names in old code. The old names suggested that XREQ was an "extended REQ" and XREP was an "extended REP" but that's inaccurate. You'll see in Chapter Three how DEALER and ROUTER sockets let you build all kinds of asynchronous request-reply flows.
  577. Now, we're just going to see how DEALER and ROUTER let us extend REQ-REP across a device, that is, our little broker.
  578. In this simple stretched request-reply pattern, REQ talks to ROUTER and DEALER talks to REP. In between the DEALER and ROUTER we have to have code (like our broker) that pulls messages off the one socket and shoves them onto the other:
  579. [[code type="textdiagram"]]
  580. +---------+ +---------+ +---------+
  581. | REQ | | REQ | | REQ |
  582. \----+----/ \----+----/ \----+----/
  583. | | |
  584. | | |
  585. +-------------+-------------+
  586. |
  587. |
  588. /-----+-----\
  589. | ROUTER |
  590. +-----------+
  591. | code |
  592. +-----------+
  593. | DEALER |
  594. \-----+-----/
  595. |
  596. |
  597. +-------------+-------------+
  598. | | |
  599. | | |
  600. /----+----\ /----+----\ /----+----\
  601. | REP | | REP | | REP |
  602. +---------+ +---------+ +---------+
  603. Figure # - Extended request-reply
  604. [[/code]]
  605. The request-reply broker binds to two endpoints, one for clients to connect to (the frontend socket) and one for services to connect to (the backend). To test this broker, you will want to change your services so they connect to the backend socket. Here are a client and service that show what I mean:
  606. [[code type="example" title="Request-reply client" name="rrclient"]]
  607. [[/code]]
  608. Here is the service:
  609. [[code type="example" title="Request-reply service" name="rrserver"]]
  610. [[/code]]
  611. And here is the broker. You will see that it's multipart safe:
  612. [[code type="example" title="Request-reply broker" name="rrbroker"]]
  613. [[/code]]
  614. Using a request-reply broker makes your client-server architectures easier to scale since clients don't see services, and services don't see clients. The only stable node is the device in the middle:
  615. [[code type="textdiagram"]]
  616. +---------+ +---------+ +---------+
  617. | | | | | |
  618. | Client | | Client | | Client |
  619. | | | | | |
  620. +---------+ +---------+ +---------+
  621. | REQ | | REQ | | REQ |
  622. \---------/ \---------/ \---------/
  623. connect connect connect
  624. | | |
  625. | | |
  626. request request request
  627. | | |
  628. +-------------+-------------+
  629. |
  630. fair-queuing
  631. |
  632. v
  633. bind
  634. /-----------\
  635. | ROUTER |
  636. +-----------+
  637. | |
  638. | Broker |
  639. | |
  640. +-----------+
  641. | DEALER |
  642. \-----------/
  643. bind
  644. |
  645. load balancing
  646. |
  647. +-------------+-------------+
  648. | | |
  649. request request request
  650. | | |
  651. v v v
  652. connect connect connect
  653. /---------\ /---------\ /---------\
  654. | REP | | REP | | REP |
  655. +---------+ +---------+ +---------+
  656. | | | | | |
  657. | Service | | Service | | Service |
  658. | A | | B | | C |
  659. | | | | | |
  660. +---------+ +---------+ +---------+
  661. Figure # - Request-reply broker
  662. [[/code]]
  663. ++++ Built-in Devices
  664. 0MQ provides some built-in devices, though most advanced users write their own devices. The built-in devices are:
  665. * QUEUE, which is like the request-reply broker.
  666. * FORWARDER, which is like the pub-sub proxy server.
  667. * STREAMER, which is like FORWARDER but for pipeline flows.
  668. To start a device, you call zmq_device[3] and pass it two sockets, one for the frontend and one for the backend:
  669. [[code language="C"]]
  670. zmq_device (ZMQ_QUEUE, frontend, backend);
  671. [[/code]]
  672. Which if you start a QUEUE device is exactly like plugging the main body of the request-reply broker into your code at that spot. You need to create the sockets, bind or connect them, and possibly configure them, before calling zmq_device[3]. It is trivial to do. Here is the request-reply broker re-written to call QUEUE and rebadged as an expensive-sounding "message queue" (people have charged houses for code that did less):
  673. [[code type="example" title="Message queue broker" name="msgqueue"]]
  674. [[/code]]
  675. The built-in devices do proper error handling, whereas the examples we have shown don't. Since you can configure the sockets as you need to, before starting the device, it's worth using the built-in devices when you can.
  676. If you're like most 0MQ users, at this stage your mind is starting to think, "//what kind of evil stuff can I do if I plug random socket types into devices?//" The short answer is: don't do it. You can mix socket types but the results are going to be weird. So stick to using ROUTER/DEALER for queue devices, SUB/PUB for forwarders and PULL/PUSH for streamers.
  677. When you start to need other combinations, it's time to write your own devices.
  678. +++ Multithreading with 0MQ
  679. 0MQ is perhaps the nicest way ever to write multithreaded (MT) applications. Whereas as 0MQ sockets require some readjustment if you are used to traditional sockets, 0MQ multithreading will take everything you know about writing MT applications, throw it into a heap in the garden, pour gasoline over it, and set it alite. It's a rare book that deserves burning, but most books on concurrent programming do.
  680. To make utterly perfect MT programs (and I mean that literally) **we don't need mutexes, locks, or any other form of inter-thread communication except messages sent across 0MQ sockets.**
  681. By "perfect" MT programs I mean code that's easy to write and understand, that works with one technology in any language and on any operating system, and that scales across any number of CPUs with zero wait states and no point of diminishing returns.
  682. If you've spent years learning tricks to make your MT code work at all, let alone rapidly, with locks and semaphores and critical sections, you will be disgusted when you realize it was all for nothing. If there's one lesson we've learned from 30+ years of concurrent programming it is: //just don't share state//. It's like two drunkards trying to share a beer. It doesn't matter if they're good buddies. Sooner or later they're going to get into a fight. And the more drunkards you add to the pavement, the more they fight each other over the beer. The tragic majority of MT applications look like drunken bar fights.
  683. The list of weird problems that you need to fight as you write classic shared-state MT code would be hilarious if it didn't translate directly into stress and risk, as code that seems to work suddenly fails under pressure. Here is a list of "//11 Likely Problems In Your Multithreaded Code//" from a large firm with world-beating experience in buggy code: forgotten synchronization, incorrect granularity, read and write tearing, lock-free reordering, lock convoys, two-step dance, and priority inversion.
  684. Yeah, we also counted seven, not eleven. That's not the point though. The point is, do you really want that code running the power grid or stock market to start getting two-step lock convoys at 3pm on a busy Thursday? Who cares what the terms actually mean. This is not what turned us on to programming, fighting ever more complex side-effects with ever more complex hacks.
  685. Some widely used metaphors, despite being the basis for billion-dollar industries, are fundamentally broken, and shared state concurrency is one of them. Code that wants to scale without limit does it like the Internet does, by sending messages and sharing nothing except a common contempt for broken programming metaphors.
  686. You should follow some rules to write happy multithreaded code with 0MQ:
  687. * You MUST NOT access the same data from multiple threads. Using classic MT techniques like mutexes are an anti-pattern in 0MQ applications. The only exception to this is a 0MQ context object, which is threadsafe.
  688. * You MUST create a 0MQ context for your process, and pass that to all threads that you want to connect via {{inproc}} sockets.
  689. * You MAY treat threads as separate tasks, with their own context, but these threads cannot communicate over {{inproc}}. However they will be easier to break into standalone processes afterwards.
  690. * You MUST NOT share 0MQ sockets between threads. 0MQ sockets are not threadsafe. Technically it's possible to do this, but it demands semaphores, locks, or mutexes. This will make your application slow and fragile. The only place where it's remotely sane to share sockets between threads are in language bindings that need to do magic like garbage collection on sockets.
  691. If you need to start more than one device in an application, for example, you will want to run each in their own thread. It is easy to make the error of creating the device sockets in one thread, and then passing the sockets to the device in another thread. This may appear to work but will fail randomly. Remember: //Do not use or close sockets except in the thread that created them.//
  692. If you follow these rules, you can quite easily split threads into separate processes, when you need to. Application logic can sit in threads, processes, boxes: whatever your scale needs.
  693. 0MQ uses native OS threads rather than virtual "green" threads. The advantage is that you don't need to learn any new threading API, and that 0MQ threads map cleanly to your operating system. You can use standard tools like Intel's ThreadChecker to see what your application is doing. The disadvantages are that your code, when it for instance starts new threads, won't be portable, and that if you have a huge number of threads (thousands), some operating systems will get stressed.
  694. Let's see how this works in practice. We'll turn our old Hello World server into something more capable. The original server was a single thread. If the work per request is low, that's fine: one ØMQ thread can run at full speed on a CPU core, with no waits, doing an awful lot of work. But realistic servers have to do non-trivial work per request. A single core may not be enough when 10,000 clients hit the server all at once. So a realistic server must start multiple worker threads. It then accepts requests as fast as it can, and distributes these to its worker threads. The worker threads grind through the work, and eventually send their replies back.
  695. You can of course do all this using a queue device and external worker processes, but often it's easier to start one process that gobbles up sixteen cores, than sixteen processes, each gobbling up one core. Further, running workers as threads will cut out a network hop, latency, and network traffic.
  696. The MT version of the Hello World service basically collapses the queue device and workers into a single process:
  697. [[code type="example" title="Multithreaded service" name="mtserver"]]
  698. [[/code]]
  699. All the code should be recognizable to you by now. How it works:
  700. * The server starts a set of worker threads. Each worker thread creates a REP socket and then processes requests on this socket. Worker threads are just like single-threaded servers. The only differences are the transport ({{inproc}} instead of {{tcp}}), and the bind-connect direction.
  701. * The server creates a ROUTER socket to talk to clients and binds this to its external interface (over {{tcp}}).
  702. * The server creates a DEALER socket to talk to the workers and binds this to its internal interface (over {{inproc}}).
  703. * The server starts a QUEUE device that connects the two sockets. The QUEUE device keeps a single queue for incoming requests, and distributes those out to workers. It also routes replies back to their origin.
  704. Note that creating threads is not portable in most programming languages. The POSIX library is {{pthreads}}, but on Windows you have to use a different API. We'll see in Chapter Three how to wrap this in a portable API.
  705. Here the 'work' is just a one-second pause. We could do anything in the workers, including talking to other nodes. This is what the MT server looks like in terms of ØMQ sockets and nodes. Note how the request-reply chain is {{REQ-ROUTER-queue-DEALER-REP}}:
  706. [[code type="textdiagram"]]
  707. +------------+
  708. | |
  709. | Client |
  710. | |
  711. +------------+
  712. | REQ |
  713. \---+--------/
  714. | ^
  715. | |
  716. "Hello" "World"
  717. | |
  718. /------------------|--=-|------------------\
  719. | v | :
  720. | /--------+---\ |
  721. | | ROUTER | |
  722. | +------------+ |
  723. | | | |
  724. | | Server | |
  725. | | | |
  726. | +------------+ |
  727. | | | |
  728. | | Queue | |
  729. | | device | |
  730. | | | |
  731. | +------------+ |
  732. | | DEALER | |
  733. | \------------/ |
  734. | ^ |
  735. | | |
  736. | +-----------+-----------+ |
  737. | | | | |
  738. | v v v |
  739. | /--------\ /--------\ /--------\ |
  740. | | REP | | REP | | REP | |
  741. | +--------+ +--------+ +--------+ |
  742. | | | | | | | |
  743. | | Worker | | Worker | | Worker | |
  744. | | | | | | | |
  745. | +--------+ +--------+ +--------+ |
  746. | |
  747. \------------------------------------------/
  748. Figure # - Multithreaded server
  749. [[/code]]
  750. +++ Signaling between Threads
  751. When you start making multithreaded applications with 0MQ, you'll hit the question of how to coordinate your threads. Though you might be tempted to insert 'sleep' statements, or use multithreading techniques such as semaphores or mutexes, **the only mechanism that you should use are 0MQ messages**. Remember the story of The Drunkards and the Beer Bottle.
  752. Here is a simple example showing three threads that signal each other when they are ready.
  753. [[code type="textdiagram"]]
  754. +------------+
  755. | |
  756. | Step 1 |
  757. | |
  758. +------------+
  759. | PAIR |
  760. \-----+------/
  761. |
  762. |
  763. Ready!
  764. |
  765. v
  766. /------------\
  767. | PAIR |
  768. +------------+
  769. | |
  770. | Step 2 |
  771. | |
  772. +------------+
  773. | PAIR |
  774. \-----+------/
  775. |
  776. |
  777. Ready!
  778. |
  779. v
  780. /------------\
  781. | PAIR |
  782. +------------+
  783. | |
  784. | Step 3 |
  785. | |
  786. +------------+
  787. Figure # - The Relay Race
  788. [[/code]]
  789. In this example we use PAIR sockets over the {{inproc}} transport:
  790. [[code type="example" title="Multithreaded relay" name="mtrelay"]]
  791. [[/code]]
  792. This is a classic pattern for multithreading with 0MQ:
  793. # Two threads communicate over {{inproc}}, using a shared context.
  794. # The parent thread creates one socket, binds it to an inproc:// endpoint, and //then// starts the child thread, passing the context to it.
  795. # The child thread creates the second socket, connects it to that inproc:// endpoint, and //then// signals to the parent thread that it's ready.
  796. Note that multithreading code using this pattern is **//not scalable out to processes//**. If you use {{inproc}} and socket pairs, you are building a tightly-bound application. Do this when low latency is really vital. For all normal apps, use one context per thread, and {{ipc}} or {{tcp}}. Then you can easily break your threads out to separate processes, or boxes, as needed.
  797. This is the first time we've shown an example using PAIR sockets. Why use PAIR? Other socket combinations might seem to work but they all have side-effects that could interfere with signaling:
  798. * You can use PUSH for the sender and PULL for the receiver. This looks simple and will work, but remember that PUSH will load-balance messages to all available receivers. If you by accident start two receivers (e.g. you already have one running and you start a second), you'll "lose" half of your signals. PAIR has the advantage of refusing more than one connection, the pair is //exclusive//.
  799. * You can use DEALER for the sender and ROUTER for the receiver. ROUTER however wraps your message in an "envelope", meaning your zero-size signal turns into a multipart message. If you don't care about the data, and treat anything as a valid signal, and if you don't read more than once from the socket, that won't matter. If however you decide to send real data, you will suddenly find ROUTER providing you with "wrong" messages. DEALER also load-balances, giving the same risk as PUSH.
  800. * You can use PUB for the sender and SUB for the receiver. This will correctly deliver your messages exactly as you sent them and PUB does not load-balance as PUSH or DEALER do. However you need to configure the subscriber with an empty subscription, which is annoying. Worse, the reliability of the PUB-SUB link is timing dependent and messages can get lost if the SUB socket is connecting while the PUB socket is sending its messages.
  801. For these reasons, PAIR makes the best choice for coordination between pairs of threads.
  802. +++ Node Coordination
  803. When you want to coordinate nodes, PAIR sockets won't work well any more. This is one of the few areas where the strategies for threads and nodes are different. Principally nodes come and go whereas threads are stable. PAIR sockets do not automatically reconnect if the remote node goes away and comes back.
  804. The second significant difference between threads and nodes is that you typically have a fixed number of threads but a more variable number of nodes. Let's take one of our earlier scenarios (the weather server and clients) and use node coordination to ensure that subscribers don't lose data when starting up.
  805. This is how the application will work:
  806. * The publisher knows in advance how many subscribers it expects. This is just a magic number it gets from somewhere.
  807. * The publisher starts up and waits for all subscribers to connect. This is the node coordination part. Each subscriber subscribes and then tells the publisher it's ready via another socket.
  808. * When the publisher has all subscribers connected, it starts to publish data.
  809. In this case we'll use a REQ-REP socket flow to synchronize subscribers and publisher. Here is the publisher:
  810. [[code type="example" title="Synchronized publisher" name="syncpub"]]
  811. [[/code]]
  812. [[code type="textdiagram"]]
  813. +----------------+
  814. | |
  815. | Publisher |
  816. | |
  817. +--------+-------+
  818. | PUB | REP |
  819. \---+----+-----+-/
  820. | ^ |
  821. | | |
  822. | (1) |
  823. [3] | |
  824. | | (2)
  825. | | |
  826. v | v
  827. /--------+-+-----\
  828. | SUB | REQ |
  829. +--------+-------+
  830. | |
  831. | Subscriber |
  832. | |
  833. +----------------+
  834. Figure # - Pub-Sub Synchronization
  835. [[/code]]
  836. And here is the subscriber:
  837. [[code type="example" title="Synchronized subscriber" name="syncsub"]]
  838. [[/code]]
  839. This Linux shell script will start ten subscribers and then the publisher:
  840. [[code]]
  841. echo "Starting subscribers..."
  842. for a in 1 2 3 4 5 6 7 8 9 10; do
  843. syncsub &
  844. done
  845. echo "Starting publisher..."
  846. syncpub
  847. [[/code]]
  848. Which gives us this satisfying output:
  849. [[code]]
  850. Starting subscribers...
  851. Starting publisher...
  852. Received 1000000 updates
  853. Received 1000000 updates
  854. Received 1000000 updates
  855. Received 1000000 updates
  856. Received 1000000 updates
  857. Received 1000000 updates
  858. Received 1000000 updates
  859. Received 1000000 updates
  860. Received 1000000 updates
  861. Received 1000000 updates
  862. [[/code]]
  863. We can't assume that the SUB connect will be finished by the time the REQ/REP dialog is complete. There are no guarantees that outbound connects will finish in any order whatsoever, if you're using any transport except {{inproc}}. So, the example does a brute-force sleep of one second between subscribing, and sending the REQ/REP synchronization.
  864. A more robust model could be:
  865. * Publisher opens PUB socket and starts sending "Hello" messages (not data).
  866. * Subscribers connect SUB socket and when they receive a Hello message they tell the publisher via a REQ/REP socket pair.
  867. * When the publisher has had all the necessary confirmations, it starts to send real data.
  868. +++ Zero Copy
  869. We teased you in Chapter One, when you were still a 0MQ newbie, about zero-copy. If you survived this far, you are probably ready to use zero-copy. However, remember that there are many roads to Hell, and premature optimization is not the most enjoyable nor profitable one, by far. In English, trying to do zero-copy properly while your architecture is not perfect is a waste of time and will make things worse, not better.
  870. 0MQ's message API lets you can send and receive messages directly from and to application buffers without copying data. Given that 0MQ sends messages in the background, zero-copy needs some extra sauce.
  871. To do zero-copy you use zmq_msg_init_data[3] to create a message that refers to a block of data already allocated on the heap with malloc(), and then you pass that to zmq_send[3]. When you create the message you also pass a function that 0MQ will call to free the block of data, when it has finished sending the message. This is the simplest example, assuming 'buffer' is a block of 1000 bytes allocated on the heap:
  872. [[code language="C"]]
  873. void my_free (void *data, void *hint) {
  874. free (data);
  875. }
  876. // Send message from buffer, which we allocate and 0MQ will free for us
  877. zmq_msg_t message;
  878. zmq_msg_init_data (&message, buffer, 1000, my_free, NULL);
  879. zmq_send (socket, &message, 0);
  880. [[/code]]
  881. There is no way to do zero-copy on receive: 0MQ delivers you a buffer that you can store as long as you wish but it will not write data directly into application buffers.
  882. On writing, 0MQ's multipart messages work nicely together with zero-copy. In traditional messaging you need to marshal different buffers together into one buffer that you can send. That means copying data. With 0MQ, you can send multiple buffers coming from different sources as individual message parts. We send each field as a length-delimited frame. To the application it looks like a series of send and recv calls. But internally the multiple parts get written to the network and read back with single system calls, so it's very efficient.
  883. +++ Transient vs. Durable Sockets
  884. In classic networking, sockets are API objects, and their lifespan is never longer than the code that uses them. But if you look at a socket you see that it collects a bunch of resources - network buffers - and at some stage, a 0MQ user asked, "isn't there some way these could hang around if my program crashes, so I can get them back?"
  885. This turns out to be very useful. It's not foolproof, but it gives 0MQ a kind of "better than a kick in the nuts" reliability, particularly useful for pub-sub cases. We'll look at that shortly.
  886. Here is the general model of two sockets happily chatting about the weather, and who kissed who and where and when precisely, cause I heard something different, at the last staff party, not to mention did you see that new family up the road who do they think they are with that car and what's with the prices at the shops these days don't they know it's a crisis?
  887. [[code type="textdiagram"]]
  888. +-----------+
  889. | |
  890. | Sender |
  891. | |
  892. +-----------+
  893. | Socket |
  894. \-----------/
  895. +---------+
  896. +---------+
  897. +---------+ 0MQ Transmit buffer
  898. +---------+
  899. +----+----+
  900. |
  901. |
  902. v
  903. +---------+
  904. +---------+ Network I/O buffers
  905. +----+----+
  906. |
  907. |
  908. v
  909. +---------+
  910. +---------+
  911. +---------+ 0MQ Receive buffer
  912. +---------+
  913. +---------+
  914. /-----------\
  915. | Socket |
  916. +-----------+
  917. | |
  918. | Receiver |
  919. | |
  920. +-----------+
  921. Figure # - Sender boring the pants off receiver
  922. [[/code]]
  923. If a //receiver// (SUB, PULL, REQ) side of a socket sets an identity, then the //sending// (PUB, PUSH, PULL) side will buffer messages when they aren't connected up to the HWM. The sending side does not need to set an identity for this to work.
  924. Note that 0MQ's transmit and receive buffers are invisible and automatic, just like TCP's buffers are.
  925. All the sockets we've used so far were transient. To turn a transient socket into a durable one you give it an explicit //identity//. All 0MQ sockets have identities but by default they are generated 'unique universal identifiers' (UUIDs) that the peer uses to recall who it's talking to.
  926. Behind the scenes, and invisibly to you, when one socket connects to another, the two sockets exchange identities. Normally sockets don't tell their peers their identity, so peers invent random identities for each other:
  927. [[code type="textdiagram"]]
  928. +-----------+
  929. | |
  930. | Sender |
  931. | |
  932. +-----------+
  933. | Socket |
  934. \-----------/
  935. ^ "Fine, I'll call you Luv"
  936. |
  937. |
  938. | "Not telling you my name!"
  939. /-----+-----\
  940. | Socket |
  941. +-----------+
  942. | |
  943. | Receiver |
  944. | |
  945. +-----------+
  946. Figure # - Transient socket
  947. [[/code]]
  948. But a socket can also tell the other its identity, and then the next time the two meet, it'll be "so as I was saying what I heard was quite different but anyhow you know how it goes at the office, they're all tattletales I'd never say anything about anyone that wasn't true or at least based on a sure thing".
  949. [[code type="textdiagram"]]
  950. +-----------+
  951. | |
  952. | Sender |
  953. | |
  954. +-----------+
  955. | Socket |
  956. \-----------/
  957. ^ "Lucy! Nice to see you again..."
  958. |
  959. |
  960. | "My name's Lucy"
  961. /-----+-----\
  962. | Socket |
  963. +-----------+
  964. | |
  965. | Receiver |
  966. | |
  967. +-----------+
  968. Figure # - Durable socket
  969. [[/code]]
  970. Here's how you set the identity of a socket, to create a durable socket:
  971. [[code language="C"]]
  972. zmq_setsockopt (socket, ZMQ_IDENTITY, "Lucy", 4);
  973. [[/code]]
  974. Some comments on setting a socket identity:
  975. * If you want to set an identity you must do it //before// connecting or binding the socket.
  976. * It's the receiver that sets an identity: it's kind of like a session cookie in an HTTP web application, except the client/sender is picking the cookie it will use.
  977. * Identities are binary strings: identities starting with a zero byte are reserved for 0MQ use.
  978. * Do not use the same identity for more than one socket. Any socket trying to connect using an identity already taken by another socket will just be disconnected.
  979. * Do not use random identities in applications that create lots of sockets. What this will do is cause lots and lots of durable sockets to pile up, eventually crashing nodes.
  980. * If you need to know the identity of the //peer// you got a message from, only the ROUTER socket does this for you automatically. For any other socket type you must send the address explicitly, as a message part.
  981. * Having said all this, using durable sockets is often a bad idea. It makes senders accumulate entropy, which makes architectures fragile. If we were making 0MQ again we'd probably not implement explicit identities at all.
  982. See zmq_setsockopt[3] for a summary of the ZMQ_IDENTITY socket option. Note that the zmq_getsockopt[3] method gives you the identity of the socket you are working with, //not// any peer it might be connected to.
  983. +++ Pub-sub Message Envelopes
  984. We've looked briefly at multipart messages. Let's now look at their main use-case, which is //message envelopes//. An envelope is a way of safely packaging up data with an address, without touching the data itself.
  985. In the pub-sub pattern, the envelope at least holds the subscription key for filtering but you can also add the sender identity in the envelope.
  986. If you want to use pub-sub envelopes, you make them yourself. It's optional, and in previous pub-sub examples we didn't do this. Using a pub-sub envelope is a little more work for simple cases but it's cleaner especially for real cases, where the key and the data are naturally separate things. It's also faster, if you are writing the data directly from an application buffer.
  987. Here is what a publish-subscribe message with an envelope looks like:
  988. [[code type="textdiagram"]]
  989. +-------------+
  990. Frame 1 | Key | Subscription key
  991. +-------------+
  992. Frame 2 | Data | Actual message body
  993. +-------------+
  994. Figure # - Pub-sub envelope with separate key
  995. [[/code]]
  996. Recall that pub-sub matches messages based on the prefix. Putting the key into a separate frame makes the matching very obvious, since there is no chance an application will accidentally match on part of the data.
  997. Here is a minimalist example of how pub-sub envelopes look in code. This publisher sends messages of two types, A and B. The envelope holds the message type:
  998. [[code type="example" title="Pub-sub envelope publisher" name="psenvpub"]]
  999. [[/code]]
  1000. The subscriber only wants messages of type B:
  1001. [[code type="example" title="Pub-sub envelope subscriber" name="psenvsub"]]
  1002. [[/code]]
  1003. When you run the two programs, the subscriber should show you this:
  1004. [[code]]
  1005. [B] We would like to see this
  1006. [B] We would like to see this
  1007. [B] We would like to see this
  1008. [B] We would like to see this
  1009. ...
  1010. [[/code]]
  1011. This examples shows that the subscription filter rejects or accepts the entire multipart message (key plus data). You won't get part of a multipart message, ever.
  1012. If you subscribe to multiple publishers and you want to know their identity so that you can send them data via another socket (and this is a fairly typical use-case), you create a three-part message:
  1013. [[code type="textdiagram"]]
  1014. +-------------+
  1015. Frame 1 | Key | Subscription key
  1016. +-------------+
  1017. Frame 2 | Identity | Address of publisher
  1018. +-------------+
  1019. Frame 3 | Data | Actual message body
  1020. +-------------+
  1021. Figure # - Pub-sub envelope with sender address
  1022. [[/code]]
  1023. +++ (Semi-)Durable Subscribers and High-Water Marks
  1024. Identities work on all socket types. If you have a PUB and a SUB socket, and the subscriber gives the publisher its identity, the publisher holds onto data until it can deliver it to the subscriber.
  1025. This is both wonderful and terrible at the same time. It's wonderful because it means updates can wait for you in the publisher's transmit buffer, until you connect and collect them. It's terrible because by default this will rapidly kill a publisher and lock up your system.
  1026. **If you use durable subscriber sockets (i.e. if you set the identity on a SUB socket) you //must// also guard against queue explosion by using the //high-water mark// or HWM, on the publisher socket.** The publisher's HWM affects all subscribers, independently.
  1027. If you want to prove this, take the wuclient and wuserver from Chapter One, and add this line to the wuclient before it connects:
  1028. [[code language="C"]]
  1029. zmq_setsockopt (subscriber, ZMQ_IDENTITY, "Hello", 5);
  1030. [[/code]]
  1031. Build and run the two programs. It all looks normal. But keep an eye on the memory used by the publisher, and you'll see that as the subscriber finishes, the publisher memory grows and grows. If you restart the subscriber, the publisher queues stop growing. As soon as the subscriber goes away, they grow again. It'll rapidly overwhelm your system.
  1032. We'll first look at how to do this, and then at how to do it properly. Here are a publisher and subscriber that use the 'node coordination' technique from Chapter Two to synchronize. The publisher then sends ten messages, waiting a second between each one. That wait is for you to kill the subscriber using Ctrl-C, wait a few seconds, and restart it.
  1033. Here's the publisher:
  1034. [[code type="example" title="Durable publisher" name="durapub"]]
  1035. [[/code]]
  1036. And here's the subscriber:
  1037. [[code type="example" title="Durable subscriber" name="durasub"]]
  1038. [[/code]]
  1039. To run this, start the publisher, then the subscriber, each in their own window. Allow the subscriber to collect one or two messages, then Ctrl-C it. Count to three, and restart it. What you will see is something like this:
  1040. [[code]]
  1041. $ durasub
  1042. Update 0
  1043. Update 1
  1044. Update 2
  1045. ^C
  1046. $ durasub
  1047. Update 3
  1048. Update 4
  1049. Update 5
  1050. Update 6
  1051. Update 7
  1052. ^C
  1053. $ durasub
  1054. Update 8
  1055. Update 9
  1056. END
  1057. [[/code]]
  1058. Just to see the difference, comment out the line in the subscriber that sets the socket identity, and try again. You will see that it loses messages. Setting an identity turns a transient subscriber into a durable subscriber. You would in practice want to choose identities carefully, either taking them from configuration files, or generating UUIDs and storing them somewhere.
  1059. When we set a high-water mark on the PUB socket, the publisher stores that many messages, but no more. Let's test this by setting the publisher HWM to 2 messages, before we start publishing to the socket:
  1060. [[code language="C"]]
  1061. uint64_t hwm = 2;
  1062. zmq_setsockopt (publisher, ZMQ_HWM, &hwm, sizeof (hwm));
  1063. [[/code]]
  1064. Now running our test, killing and restarting the subscriber after a couple of seconds' pause will show something like this:
  1065. [[code]]
  1066. $ durasub
  1067. Update 0
  1068. Update 1
  1069. ^C
  1070. $ durasub
  1071. Update 2
  1072. Update 3
  1073. Update 7
  1074. Update 8
  1075. Update 9
  1076. END
  1077. [[/code]]
  1078. Look carefully: we have two messages kept for us (2 and 3), then a gap of several messages, and then new updates again. The HWM causes 0MQ to drop messages it can't put onto the queue, something the 0MQ Reference Manual calls an "exceptional condition".
  1079. In short, if you use subscriber identities, you must set the high-water mark on publisher sockets, or else you risk servers that run out of memory and crash. However, there is a way out. 0MQ provides something called a "swap", which is a disk file that holds messages we can't store to the queue. It is very simple to enable:
  1080. [[code language="C"]]
  1081. // Specify swap space in bytes
  1082. uint64_t swap = 25000000;
  1083. zmq_setsockopt (publisher, ZMQ_SWAP, &swap, sizeof (swap));
  1084. [[/code]]
  1085. We can put this together to make a cynical publisher that is immune to slow, blocked, or absent subscribers while still offering durable subscriptions to those that need it:
  1086. [[code type="example" title="Durable but cynical publisher" name="durapub2"]]
  1087. [[/code]]
  1088. In practice, setting the HWM to 1 and shoving everything to disk will make a pub-sub system very slow. Here is a more reasonable 'best practice' for publishers that have to deal with unknown subscribers:
  1089. * **Always set a HWM on the PUB socket**, based on the expected maximum number of subscribers, the amount of memory you are willing to dedicate to queuing, and the average size of a message. For example if you expect up to 5,000 subscribers, and have 1GB of memory to play with, and messages of ~200 bytes, then a safe HWM would be (1,000,000,000 / 200 / 5,000) = 1,000.
  1090. * If you don't want slow or crashing subscribers to lose data, set a SWAP that's large enough to handle the peaks, based on the number of subscribers, peak message rate, average size of messages, and time you want to cover. For example with 5,000 subscribers and messages of ~200 bytes coming in at 100,000 per second, you will need up to 100MB of disk space per second. To cover an outage of up to 1 minute, therefore, you'd need 6GB of disk space, and it would have to be fast, but that's a different story.
  1091. Some notes on durable subscribers:
  1092. * Depending on how the subscriber dies, and the frequency of updates, and the size of network buffers, and the transport protocol you are using, data may be lost. Durable subscribers will have //much better// reliability than transient ones, but they will not be perfect.
  1093. * The SWAP file is not recoverable, so if a publisher dies and restarts, it will lose data that was in its transmit buffers, and that was in the network I/O buffers.
  1094. Some notes on using the HWM option:
  1095. * This affects both the transmit and receive buffers of a single socket. Some sockets (PUB, PUSH) only have transmit buffers. Some (SUB, PULL, REQ, REP) only have receive buffers. Some (DEALER, ROUTER, PAIR) have both transmit and receive buffers.
  1096. * When your socket reaches its high-water mark, it will either block or drop data depending on the socket type. PUB sockets will drop data if they reach their high-water mark, while other socket types will block.
  1097. * Over the {{inproc}} transport, the sender and receiver share the same buffers, so the real HWM is the sum of the HWM set by both sides. This means in effect that if one side does not set a HWM, there is no limit to the buffer size.
  1098. +++ A Bare Necessity
  1099. ØMQ is like a box of pieces that plug together, the only limitation being your imagination and sobriety.
  1100. The scalable elastic architecture you get should be an eye-opener. You might need a coffee or two first. Don't make the mistake I made once and buy exotic German coffee labeled //Entkoffeiniert//. That does not mean "Delicious". Scalable elastic architectures are not a new idea - [http://en.wikipedia.org/wiki/Flow-based_programming flow-based programming] and languages like [http://www.erlang.org/ Erlang] already worked like this - but ØMQ makes it easier to use than ever before.
  1101. As [http://permalink.gmane.org/gmane.network.zeromq.devel/2145 Gonzo Diethelm said], '//My gut feeling is summarized in this sentence: "if ØMQ didn't exist, it would be necessary to invent it". Meaning that I ran into ØMQ after years of brain-background processing, and it made instant sense... ØMQ simply seems to me a "bare necessity" nowadays.//'