Reactor pattern

The reactor software design pattern is an event handling strategy that can respond to many potential service requests concurrently. The pattern's key component is an event loop, running in a single thread or process, which demultiplexes incoming requests and dispatches them to the correct request handler.[1]

By relying on event-based mechanisms rather than blocking I/O or multi-threading, a reactor can handle many concurrent I/O bound requests with minimal delay.[2] A reactor also allows for easily modifying or expanding specific request handler routines, though the pattern does have some drawbacks and limitations.[1]

With its balance of simplicity and scalability, the reactor has become a central architectural element in several server applications and software frameworks for networking. Derivations such as the multireactor and proactor also exist for special cases where even greater throughput, performance, or request complexity are necessary.[1][2][3][4]

Overview

Practical considerations for the client–server model in large networks, such as the C10k problem for web servers, were the original motivation for the reactor pattern.[5]

A naive approach to handle service requests from many potential endpoints, such as network sockets or file descriptors, is to listen for new requests from within an event loop, then immediately read the earliest request. Once the entire request has been read, it can be processed and forwarded on by directly calling the appropriate handler. An entirely "iterative" server like this, which handles one request from start-to-finish per iteration of the event loop, is logically valid. However, it will fall behind once it receives multiple requests in quick succession. The iterative approach cannot scale because reading the request blocks the server's only thread until the full request is received, and I/O operations are typically much slower than other computations.[2]

One strategy to overcome this limitation is multi-threading: by immediately splitting off each new request into its own worker thread, the first request will no longer block the event loop, which can immediately iterate and handle another request. This "thread per connection" design scales better than a purely iterative one, but it still contains multiple inefficiencies and will struggle past a point. From a standpoint of underlying system resources, each new thread or process imposes overhead costs in memory and processing time (due to context switching). The fundamental inefficiency of each thread waiting for I/O to finish isn't resolved either.[1][2]

From a design standpoint, both approaches tightly couple the general demultiplexer with specific request handlers too, making the server code brittle and tedious to modify. These considerations suggest a few major design decisions:

  1. Retain a single-threaded event handler; multi-threading introduces overhead and complexity without resolving the real issue of blocking I/O
  2. Use an event notification mechanism to demultiplex requests only after I/O is complete (so I/O is effectively non-blocking)
  3. Register request handlers as callbacks with the event handler for better separation of concerns

Combining these insights leads to the reactor pattern, which balances the advantages of single-threading with high throughput and scalability.[1][2]

Usage

The reactor pattern can be a good starting point for any concurrent, event-handling problem. The pattern is not restricted to network sockets either; hardware I/O, file system or database access, inter-process communication, and even abstract message passing systems are all possible use-cases.[citation needed]

However, the reactor pattern does have limitations, a major one being the use of callbacks, which make program analysis and debugging more difficult, a problem common to designs with inverted control.[1] The simpler thread-per-connection and fully iterative approaches avoid this and can be valid solutions if scalability or high-throughput are not required.[a][citation needed]

Single-threading can also become a drawback in use-cases that require maximum throughput, or when requests involve significant processing. Different multi-threaded designs can overcome these limitations, and in fact, some still use the reactor pattern as a sub-component for handling events and I/O.[1]

Applications

The reactor pattern (or a variant of it) has found a place in many web servers, application servers, and networking frameworks:

Structure

A reactive application consists of several moving parts and will rely on some support mechanisms:[1]

Handle
An identifier and interface to a specific request, with IO and data. This will often take the form of a socket, file descriptor, or similar mechanism, which should be provided by most modern operating systems.
Demultiplexer
An event notifier that can efficiently monitor the status of a handle, then notify other subsystems of a relevant status change (typically an IO handle becoming "ready to read"). Traditionally this role was filled by the select() system call, but more contemporary examples include epoll, kqueue, and IOCP.
Dispatcher
The actual event loop of the reactive application, this component maintains the registry of valid event handlers, then invokes the appropriate handler when an event is raised.
Event Handler
Also known as a request handler, this is the specific logic for processing one type of service request. The reactor pattern suggests registering these dynamically with the dispatcher as callbacks for greater flexibility. By default, a reactor does not use multi-threading but invokes a request handler within the same thread as the dispatcher.
Event Handler Interface
An abstract interface class, representing the general properties and methods of an event handler. Each specific handler must implement this interface while the dispatcher will operate on the event handlers through this interface.

Variants

The standard reactor pattern is sufficient for many applications, but for particularly demanding ones, tweaks can provide even more power at the price of extra complexity.

One basic modification is to invoke event handlers in their own threads for more concurrency. Running the handlers in a thread pool, rather than spinning up new threads as needed, will further simplify the multi-threading and minimize overhead. This makes the thread pool a natural complement to the reactor pattern in many use-cases.[2]

Another way to maximize throughput is to partly reintroduce the approach of the "thread per connection" server, with replicated dispatchers / event loops running concurrently. However, rather than the number of connections, one configures the dispatcher count to match the available CPU cores of the underlying hardware.

Known as a multireactor, this variant ensures a dedicated server is fully using the hardware's processing power. Because the distinct threads are long-running event loops, the overhead of creating and destroying threads is limited to server startup and shutdown. With requests distributed across independent dispatchers, a multireactor also provides better availability and robustness; should an error occur and a single dispatcher fail, it will only interrupt requests allocated to that event loop.[3][4]

For particularly complex services, where synchronous and asynchronous demands must be combined, one other alternative is the proactor pattern. This pattern is more intricate than a reactor, with its own engineering details, but it still makes use of a reactor subcomponent to solve the problem of blocking IO.[3]

See also

Related patterns:

Notes

  1. ^ That said, a rule-of-thumb in software design is that if application demands can potentially increase past an assumed limit, one should expect that someday they will.

References

  1. ^ a b c d e f g h i j k Schmidt, Douglas C. (1995). "Chapter 29: Reactor: An Object Behavioral Pattern for Demultiplexing and Dispatching Handles for Synchronous Events" (PDF). In Coplien, James O. (ed.). Pattern Languages of Program Design. Vol. 1 (1st ed.). Addison-Wesley. ISBN 9780201607345.
  2. ^ a b c d e f g Devresse, Adrien (20 June 2014). "Efficient parallel I/O on multi-core architectures" (PDF). 2nd Thematic CERN School of Computing. CERN. Archived (PDF) from the original on 8 August 2022. Retrieved 14 September 2023.
  3. ^ a b c d e Escoffier, Clement; Finnegan, Ken (November 2021). "Chapter 4. Design Principles of Reactive Systems". Reactive Systems in Java. O'Reilly Media. ISBN 9781492091721.
  4. ^ a b c Garrett, Owen (10 June 2015). "Inside NGINX: How We Designed for Performance & Scale". NGINX. F5, Inc. Archived from the original on 20 August 2023. Retrieved 10 September 2023.
  5. ^ Kegel, Dan (5 February 2014). "The C10k problem". Dan Kegel's Web Hostel. Archived from the original on 6 September 2023. Retrieved 10 September 2023.
  6. ^ Bonér, Jonas (15 June 2022). "The Reactive Patterns: 3. Isolate Mutations". The Reactive Principles. Retrieved 20 September 2023.
  7. ^ "Network Programming: Writing network and internet applications" (PDF). POCO Project. Applied Informatics Software Engineering GmbH. 2010. pp. 21–22. Retrieved 20 September 2023.
  8. ^ Stoyanchev, Rossen (9 February 2016). "Reactive Spring". Spring.io. Retrieved 20 September 2023.
  9. ^ "Reactor Overview". twisted.org. Retrieved 28 July 2024.

Specific applications:

Sample implementations:

Read other articles:

City in Baden-Württemberg, Germany Freiburg redirects here. For Freiberg in Saxony, see Freiberg. For Fribourg in Switzerland, see Fribourg. For the French hamlet, see Friburge. For other uses, see Freiburg (disambiguation). This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Freiburg im Breisgau – news · newspapers · book...

Dolina Rybiego Potoku Dolina Rybiegi Potoku vom Gipfel Rysy Dolina Rybiegi Potoku vom Gipfel Rysy Lage Woiwodschaft Kleinpolen, Polen Gewässer Rybi Potok Gebirge Hohe Tatra, Tatra, Karpaten Geographische Lage 49° 12′ 42″ N, 20° 4′ 46″ O49.21166666666720.0794444444442503Koordinaten: 49° 12′ 42″ N, 20° 4′ 46″ O Dolina Rybiego Potoku (Kleinpolen) Höhe 1400 bis 2503 m n.p.m. Länge 6 km Klim...

De talkbox van Peter Frampton Een talkbox of jappiotube is een apparaat waarmee geluidseffecten kunnen worden opgewekt. De uitvinding wordt zowel door Bob Heil als door Doug Forbes geclaimd. Het apparaat bestaat uit een luidspreker waaraan een kunststof slang is verbonden, en wordt bediend met een voetschakelaar waarmee het geluid van het instrument naar keuze naar een gewone luidspreker kan worden gestuurd of naar de talkbox. Via de slang wordt het geluid van een aangesloten instrument in de...

This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages) This article includes a list of general references, but it lacks sufficient corresponding inline citations. Please help to improve this article by introducing more precise citations. (June 2012) (Learn how and when to remove this template message) This article relies excessively on references to primary sources. Please improve this article b...

Former pan-European cable and satellite sports television network (1984–1993) For indoor sports, see screen sports. Television channel ScreensportSportkanalSportnetTV SportCountryEuropeBroadcast areaUnited KingdomProgrammingLanguage(s)DutchEnglishSpanishFrenchGermanOwnershipOwnerWHSTV (WHSmith)ESPN Inc.[1]HistoryLaunched29 March 1984Closed1 March 1993[2]Replaced byEurosport Screensport was a pan-European cable and satellite sports television network that was on air from 1984...

KamaruddinKaro Ops Polda SumselMasa jabatan3 Agustus 2020 – 24 Juni 2023PendahuluDjihartonoPenggantiReeza Herasbudi Informasi pribadiLahir0 Januari 1968 (umur 55)Makassar, Sulawesi SelatanSuami/istriNy. Ita KamaruddinAlma materAkademi Kepolisian (1990)Karier militerPihak IndonesiaDinas/cabang Lembaga Ketahanan NasionalMasa dinas1990—sekarangPangkat Komisaris Besar PolisiSatuanBrigade MobilSunting kotak info • L • B Brigjen. Pol. Kamaruddin, M.Si. (lah...

Cet article dresse la liste des aéroports les plus fréquentés en Équateur, d'après la principale source[1] : En graphique Pour des raisons techniques, il est temporairement impossible d'afficher le graphique qui aurait dû être présenté ici. Voir la requête brute et les sources sur Wikidata. Tableau du total de la fréquentation Ce tableau indique le total de la fréquentation en passagers aériens internationaux du pays par année[2] Année Passagers 2009 1347647 2010 1474850 2...

Historic district in California, United States United States historic placeLassen Volcanic National Park Highway Historic DistrictU.S. National Register of Historic PlacesU.S. Historic district Show map of CaliforniaShow map of the United StatesNearest cityMineral, CaliforniaArea290 acres (120 ha)Built1926ArchitectFrank C. Hewitt et al.Architectural styleNPS RusticMPSLassen Volcanic National Park MPSNRHP reference No.06000527[1]Added to NRHPJune 23, 2006 The Lassen...

American TV series or program I Love the '70s: Volume 2GenreDocumentaryNarrated byDoug JeffersCountry of originUnited StatesOriginal languageEnglishNo. of seasons1No. of episodes10ProductionRunning time60 minutesOriginal releaseNetworkVH1ReleaseJuly 10 (2006-07-10) –July 14, 2006 (2006-07-14)RelatedI Love the '80sI Love the '70sI Love the '80s Strikes BackI Love the '90sI Love the '90s: Part DeuxI Love the '80s 3-DI Love the HolidaysI Love ToysI Love the New MillenniumBe...

Сервер HP ProLiant 380 G5 ProLiant — торговая марка серверов, разработанных и распространявшихся фирмой Compaq с осени 1993 года[1]. Линейка сменила предыдущий бренд серверов верхнего сегмента от Compaq — SystemPro XL. После поглощения корпорацией Hewlett-Packard марка сохранена и развивается...

Numerous settlements lost to sea enroachment in the Netherlands are listed. This list of settlements lost to floods in the Netherlands is an adapted translation of this list from Dutch, plus some additions from other sources. Oud- is Dutch for Old. If you cannot find a name, look for it under Oud-. Drowned villages and places in Zeeland and West-Brabant Name Description Aandijke (also Aendike) Drowned village in Zeelandic Flanders. On the former island of Zaamslag. Assenburg Small village on ...

Boom brake with line. The brake shackles to the bottom of the boom, and the line attaches to the base of the shrouds; tensioning the line actuates the brake. A boom brake is a device designed to control the swing of the boom on a sailboat. The boom brake acts as a preventer when sailing downwind, and can also be used to jibe(US) or gybe(UK) the mainsail in a slow measured action. Uncontrolled jibes often damage elements of the rig, and can inflict serious and sometimes fatal injuries to crew ...

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (يونيو 2019) ديك أيرز (بالإنجليزية: Dick Ayers)‏    معلومات شخصية الميلاد 28 أبريل 1924[1][2]  أوسينينغ، نيويورك  الوفاة 4 مايو 2014 (90 سنة) [1][2]  وايت بلينس...

Artikel ini perlu diwikifikasi agar memenuhi standar kualitas Wikipedia. Anda dapat memberikan bantuan berupa penambahan pranala dalam, atau dengan merapikan tata letak dari artikel ini. Untuk keterangan lebih lanjut, klik [tampil] di bagian kanan. Mengganti markah HTML dengan markah wiki bila dimungkinkan. Tambahkan pranala wiki. Bila dirasa perlu, buatlah pautan ke artikel wiki lainnya dengan cara menambahkan [[ dan ]] pada kata yang bersangkutan (lihat WP:LINK untuk keterangan lebih lanjut...

إبراهيم‌ بيغي (بالفارسية: ابراهيم بيگي)‏  تقسيم إداري البلد إيران  [1] خصائص جغرافية إحداثيات 35°55′26″N 50°39′00″E / 35.923889°N 50.65°E / 35.923889; 50.65  الارتفاع 1215 متر  السكان التعداد السكاني 652 نسمة (إحصاء 2016) الرمز الجغرافي 41730  تعديل مصدري - تعديل   إبراهيم...

Local municipality in Western Cape, South AfricaTheewaterskloofLocal municipality SealLocation in the Western CapeCoordinates: 34°10′S 19°30′E / 34.167°S 19.500°E / -34.167; 19.500CountrySouth AfricaProvinceWestern CapeDistrictOverbergSeatCaledonWards13Government[1] • TypeMunicipal council • MayorKallie Papier (PA)Area • Total3,232 km2 (1,248 sq mi)Population (2011)[2] • Total10...

Nepal padaOlimpiadeKode IOCNEPKONKomite Olimpiade NepalSitus webwww.nocnepal.org.npMedali 0 0 0 Total 0 Penampilan Musim Panas196419681972197619801984198819921996200020042008201220162020Penampilan Musim Dingin200220062010201420182022 Nepal berkompetisi dalam dua belas Olimpiade Musim Panas dan empat Olimpiade Musim Dingin. Komite Olimpiade Nepal dibentuk pada 1962 dan diresmikan pada 1963. Referensi Pranala luar Nepal. International Olympic Committee.  Nepal. Sports-Reference.com. Diarsi...

Cầu Sông Zohar Cầu Sông Zohar (tiếng Hebrew: גֶּשֶׁר זֹהַר‎, Gesher Zohar) là một cây cầu nằm trên tuyến Quốc lộ 90 gần Biển Chết tại Israel. Nếu tính theo mực nước biển, đây là cây cầu thấp nhất trên thế giới. Cây cầu có độ cao khoảng 40 mét tính từ mặt sông, cầu có chiều dài là 52 mét. [1] Xem thêm Neve Zohar Tham khảo ^ Bridges and Civil Engineering Structures Lưu trữ 2011-07-21 ...

American basketball broadcaster Christy Winters–Scott Christy Winters Scott is a basketball color analyst for college basketball games for ESPN, FSN, The Big Ten Network (BTN), NBC Sports Washington, and Raycom Sports. She has been the lead analyst for BTN Women’s Basketball since 2016. Some of her earlier jobs were: to serve as an analyst for ACC Women's games, the ACC Women's Basketball Tournament, SEC games, and she has been serving as an analyst for the NCAA women's basketball tournam...

Provisional State Council מועצת המדינה הזמנית‎Moetzet HaMedina HaZmanitTypeTypeUnicameral HistoryFounded12 April 1948Disbanded3 February 1949LeadershipCouncil PresidentChaim Weizmann (1948–1949), General Zionists Council SpeakerYosef Sprinzak, Mapai Prime MinisterDavid Ben-Gurion, Mapai StructureSeats37Political groupsProvisional government (30)   Mapai (10)   Mapam (3)   General Zionists (3)   New Aliyah (3)   Mizrachi (3)   ...