In software architecture, publish–subscribe is a messaging pattern where publishers categorize messages into classes that are received by subscribers. This is contrasted to the typical messaging pattern model where publishers sends messages directly to subscribers.

Similarly, subscribers express interest in one or more classes and only receive messages that are of interest, without knowledge of which publishers, if any, there are.

Publish–subscribe is a sibling of the message queue paradigm, and is typically one part of a larger message-oriented middleware system. Most messaging systems support both the pub/sub and message queue models in their API; e.g., Java Message Service (JMS).

This pattern provides greater network scalability and a more dynamic network topology, with a resulting decreased flexibility to modify the publisher and the structure of the published data.

Message filtering

In the publish-subscribe model, subscribers typically receive only a subset of the total messages published. The process of selecting messages for reception and processing is called filtering. There are two common forms of filtering: topic-based and content-based.

In a topic-based system, messages are published to "topics" or named logical channels. Subscribers in a topic-based system will receive all messages published to the topics to which they subscribe. The publisher is responsible for defining the topics to which subscribers can subscribe.

In a content-based system, messages are only delivered to a subscriber if the attributes or content of those messages matches constraints defined by the subscriber. The subscriber is responsible for classifying the messages.

Some systems support a hybrid of the two; publishers post messages to a topic while subscribers register content-based subscriptions to one or more topics.

Topologies
In many publish-subscribe systems, publishers post messages to an intermediary  message broker or event bus, and subscribers register subscriptions with that broker, letting the broker perform the filtering. The broker normally performs a store and forward function to route messages from publishers to subscribers. In addition, the broker may prioritize messages in a queue before routing.

Subscribers may register for specific messages at build time, initialization time or runtime. In GUI systems, subscribers can be coded to handle user commands (e.g., click of a button), which corresponds to build time registration. Some frameworks and software products use XML configuration files to register subscribers. These configuration files are read at initialization time. The most sophisticated alternative is when subscribers can be added or removed at runtime. This latter approach is used, for example, in database triggers, mailing lists, and RSS.

The Data Distribution Service (DDS) middleware does not use a broker in the middle. Instead, each publisher and subscriber in the pub/sub system shares meta-data about each other via IP multicast. The publisher and the subscribers cache this information locally and route messages based on the discovery of each other in the shared cognizance. In effect, brokerless architectures require publish/subscribe system to construct an overlay network which allows efficient decentralized routing from publishers to subscribers. It was shown by Jon Kleinberg that efficient decentralised routing requires Navigable Small-World topologies. Such Small-World topologies are usually implemented by decentralized or federated publish/subscribe systems. Locality-aware publish/subscribe systems construct Small-World topologies that route subscriptions through short-distance and low-cost links thereby reducing subscription delivery times.

History
One of the earliest publicly described pub/sub systems was the "news" subsystem of the Isis Toolkit, described at the 1987 Association for Computing Machinery (ACM) Symposium on Operating Systems Principles conference (SOSP '87), in a paper "Exploiting Virtual Synchrony in Distributed Systems. 123–138".

Advantages

Loose coupling
Publishers are loosely coupled to subscribers, and need not even know of their existence. With the topic being the focus, publishers and subscribers are allowed to remain ignorant of system topology. Each can continue to operate as per normal independently of the other. In the traditional tightly coupled client–server paradigm, the client cannot post messages to the server while the server process is not running, nor can the server receive messages unless the client is running. Many pub/sub systems decouple not only the locations of the publishers and subscribers but also decouple them temporally. A common strategy used by middleware analysts with such pub/sub systems is to take down a publisher to allow the subscriber to work through the backlog (a form of bandwidth throttling).

Scalability
Pub/sub provides the opportunity for better scalability than traditional client-server, through parallel operation, message caching, tree-based or network-based routing, etc. However, in certain types of tightly coupled, high-volume enterprise environments, as systems scale up to become data centers with thousands of servers sharing the pub/sub infrastructure, current vendor systems often lose this benefit; scalability for pub/sub products under high load in these contexts is a research challenge.

Outside of the enterprise environment, on the other hand, the pub/sub paradigm has proven its scalability to volumes far beyond those of a single data center, providing Internet-wide distributed messaging through web syndication protocols such as RSS and Atom.  These syndication protocols accept higher latency and lack of delivery guarantees in exchange for the ability for even a low-end web server to syndicate messages to (potentially) millions of separate subscriber nodes.

Disadvantages

The most serious problems with pub/sub systems are a side-effect of their main advantage: the decoupling of publisher from subscriber.

Message delivery issues
A pub/sub system must be designed carefully to be able to provide stronger system properties that a particular application might require, such as assured delivery.
  The broker in a pub/sub system may be designed to deliver messages for a specified time, but then stop attempting delivery, whether or not it has received confirmation of successful receipt of the message by all subscribers. A pub/sub system designed in this way cannot guarantee delivery of messages to any applications that might require such assured delivery. Tighter coupling of the designs of such a publisher and subscriber pair must be enforced outside of the pub/sub architecture to accomplish such assured delivery (e.g. by requiring the subscriber to publish receipt messages).
  A publisher in a pub/sub system may assume that a subscriber is listening, when in fact it is not. A factory may utilize a pub/sub system where equipment can publish problems or failures to a subscriber that displays and logs those problems. If the logger fails (crashes), equipment problem publishers won't necessarily receive notice of the logger failure, and error messages will not be displayed or recorded by any equipment on the pub/sub system. This is also a design challenge for alternative messaging architectures, such as a client/server system. In a client/server system, when an error logger fails, the system will receive an indication of the error logger (server) failure. However, the client/server system will have to deal with that failure by having redundant logging servers online, or by dynamically spawning fallback logging servers. This adds complexity to the client and server designs, as well as to the client/server architecture as a whole. However, in a pub/sub system, redundant logging subscribers that are exact duplicates of the existing logger can be added to the system to increase logging reliability without any impact to any other equipment on the system. In a pub/sub system, the feature of assured error message logging can be added incrementally, subsequent to implementing the basic functionality of equipment problem message logging.

The pub/sub pattern scales well for small networks with a small number of publisher and subscriber nodes and low message volume. However, as the number of nodes and messages grows, the likelihood of instabilities increases, limiting the maximum scalability of a pub/sub network. Example throughput instabilities at large scales include:
 Load surges—periods when subscriber requests saturate network throughput followed by periods of low message volume (underutilized network bandwidth)
 Slowdowns—as more and more applications use the system (even if they are communicating on separate pub/sub channels) the message volume flow to an individual subscriber will slow

For pub/sub systems that use brokers (servers), the argument for a broker to send messages to a subscriber is in-band, and can be subject to security problems. Brokers might be fooled into sending notifications to the wrong client, amplifying denial of service requests against the client. Brokers themselves could be overloaded as they allocate resources to track created subscriptions.

Even with systems that do not rely on brokers, a subscriber might be able to receive data that it is not authorized to receive. An unauthorized publisher may be able to introduce incorrect or damaging messages into the pub/sub system. This is especially true with systems that broadcast or multicast their messages.  Encryption (e.g. Transport Layer Security (SSL/TLS)) can prevent unauthorized access, but cannot prevent damaging messages from being introduced by authorized publishers. Architectures other than pub/sub, such as client/server systems, are also vulnerable to authorized message senders that behave maliciously.

See also
 Atom, another highly scalable web-syndication protocol
 Data Distribution Service (DDS)
 Event-driven programming
 High-level architecture
 Internet Group Management Protocol (IGMP)
 Message brokers
 Message queue
 Observer pattern
 Producer–consumer problem
 Push technology
 RSS, a highly scalable web-syndication protocol
 Usenet
 WebSub, an implementation of pub/sub

References

Architectural pattern (computer science)
Distributed computing architecture
Message-oriented middleware
Software design patterns
발행-구독 모델은 비동기 메시징 패러다임이다. 발행-구독 모델에서 발신자의 메시지는 특별한 수신자가 정해져 있지 않다. 대신 발행된 메시지는 정해진 범주에 따라, 각 범주에 대한 구독을 신청한 수신자에게 전달된다. 수신자는 발행자에 대한 지식이 없어도 원하는 메시지만을 수신할 수 있다. 이러한 발행자와 구독자의 디커플링은 더 다이나믹한 네트워크 토폴로지와 높은 확장성을 허용한다.

발행-구독은 메시지 큐 패러다임과 형제같은 관계로, 일반적으로 대형 메시지 지향 미들웨어 솔루션의 일부이다. 대부분의 메시징 시스템의 API(예: JMS)들은 발행-구독과 메시지 큐 모델을 모두 지원한다.

메시지 필터링
발행/구독 모델에서 구독은 이론적으로 전체 발행된 메시지의 부분집합만을 받는다. 수신자 별로 메시지를 분류하는 프로세스와 처리를 필터링이라 부른다. 필터링에는 일반적으로 토픽 기반과 콘텐츠 기반의 2가지 형태가 있다. 토픽 기반 시스템에서 메시지는 "토픽"으로 발행되거나 논리 채널들로 명명된다. 토픽 기반 시스템에서 수신자는 구독하고자 하는 모든 발행 메시지들을 받는다. 그리고 해당 토픽의 수신자들은 모두 같은 메시지를 받을 것이다. 발행자는 구독자가 구독할 메시지의 클래스를 정의한다. 콘텐츠 기반 시스템에서, 메시지는 구독자에 의해 정의된 메시지 콘텐츠나 속성의 제한적 일치시에 전달된다. 구독자는 메시지를 분류할 책임이 있다.

토폴로지
많은 발행/구독 시스템에서 발행자는 중개 브로커에게 메시지를 전달한다. 그리고 구독자들은 해당 브로커에 구독을 등록한다. 브로커는 일반적으로 발행자들로부터 구독자들에게 store-and-forward 명령을 이용하여 메시지를 전달할 루트를 정한다. 또 다른 발행/구독 시스템에서는 분산 라우팅과 필터링 기능에 의해 발행자와 구독자 사이의 메시지 브로커를 제거하였다. 때때로 데몬의 도움이 요구된다. 특별히 고성능옵션을 포함하는 발행/구독 토픽들은 IP 멀티캐스트 그룹들에 맵핑된다. 그래서 데이터는 발행자로부터 구독자들에게 직접적으로 전달될 수 있다. 콘텐츠 기반의 필터링은 메시지가 애플리케이션 레이어로 전달되기 전에 구독자 내에서 수행될 수 있다.

역사
최초의 발행-구독 시스템은 Isis 툴킷내의 "뉴스" 부 시스템이었고, 1987년 ACM심포지움의 OS 구조 컨퍼런스에서 발표되었다. 논문은 "Exploiting Virtual Synchrony in Distributed Systems. 123-138"이다. 발행-구독 기술은 완전한 기능적 발행-구독 솔루션을 개발한 최초의 사람으로 명성을 얻은 프랭크 슈먹(Frank Schmuck)에 의해 개발되었다.

장점
느슨한 결합:발행자는 구독자들과 느슨하게 결합되고, 서로의 존재를 알 필요가 없다. 관심사는 토픽에 있고, 발행자와 구독자는 시스템 토폴로지를 몰라도 상관이 없다. 각각은 서로를 고려하지 않은 채 동작을 지속할 수 있다. 전통적으로 강하게 결합된 클라이언트-서버 패러다임에서는 서버 프로세스가 Running 상태가 아니면 클라이언트가 서버로 메시지를 보낼 수 없고 서버또한 클라이언트가 동작하기 전까지는 메시지를 받을 수 없다. 많은 발행-구독 시스템은 발행자와 구독자간의 위치뿐만 아니라, 일시적인 것들까지도 모두 디커플링한다.

확장성:연관된 작은환경의 설치에서, 발행-구독은 병렬 수행, 메시지 캐싱, 트리기반 또는 네트워크기반 라우팅 등을 통해 전통적인 클라이언트-서버 구조 보다 더 나은 확장성의 기회를 제공한다. 그러나, 시스템들이 수천개의 데이터 센터급으로 확장되어 발행-구독 기반으로 공유될 때 이러한 장점이 간혹 상실된다. 사실상, 대형배치, 고부하 하에서의 발행-구독 제품에서의 확장성은 연구 도전거리이다.

단점
대부분의 발행-구독 시스템의 심각한 문제는 그들이 갖는 주된 장점에 대한 부작용이다. 구독자로부터 발행자가 디커플링되는 경우 문제는 이것이 애플리케이션에서 엔드투엔드에서 필요로 할 수 있는 강한 속성 명세가 어렵다는 점이다. 브로커를 이용하는 발행-구독 시스템에서 구독자에게 메시지를 보내기 위해 브로커의 동의는 in-band이고 보안 문제가 야기될 수 있다. 브로커는 잘못된 클라이언트에 알림을 보낼 수 있고, 클라이언트에 대해 서비스 거부에 대해 과장할 수 있다. 브로커는 생성된 구독에 대해 추적하기 위해 리소스를 할당하여 과부하 될 수 있다. 시스템이 브로커에 의존하지 않더라도 구독자는 받기 허락되지 않은 데이터를 받을 수 있다. 허락되지 않은 발행자가 잘못거나 손상된 메시지를 발행/구독 시스템 내에서 발표할 수 있다. 특히 이러한 문제는 브로드캐스트나 멀티캐스트에서의 메시지에서 발생한다. 암호화(예: SSL/TLS) 가 미인증 접근으로부터 강한 보호를 할 수 있다.

발행/구독 모델을 구현한 미들웨어
 턱시도 : 확장성과 트랜잭션의 발행/구독 가용성을 제공하는 트랜잭션 처리 시스템

같이 보기 
 데이터 분산 서비스
 푸시 풀 전략

아키텍처 패턴
메시지 지향 미들웨어