Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

ISUG SSB Lior King


Published on

  • Be the first to comment

ISUG SSB Lior King

  1. 1. Introduction to Service Broker inSQL Server 2005/2008<br />Lior King<br />Database & Infrastructure Group Manager<br />SRL Group<br />
  2. 2. 2<br />Agenda<br />Messaging, SOA, SODA.<br />What is Service Broker (SB) and is it good for.<br />Microsoft’s alternatives to Service Broker.<br />Messaging Basics: Conversation, Dialogs, Conversation Groups, Service<br />SB building blocks: Message types, Contracts, Queues, Service programs.<br />Messaging flow.<br />Handling errors and poison messages.<br />Internal & External activation<br />Using conversations group lock.<br />Routing and security<br />
  3. 3. 3<br />Why Messaging?<br />Asynchronous message processing <br />Decoupling long duration business processes from the client app. For example: Sending a letter or an email.<br />Getting scalability.<br />Benefits of deferred message processing:<br />The receiver controls when messages are processed.<br />Load balancing occurs during peak times.<br />Fault tolerance on the receiving side.<br />Vital for Distributed Systems.<br />Software components are running on different servers on the network<br />Enabling scalability<br />Handling security issues: Authentication, Encryption.<br />
  4. 4. 4<br />What is SOA?<br />SOA = Service Oriented Architecture.<br />Explicit Service boundaries<br />Exposing the available operations to other clients.<br />Autonomous services.<br />Minimum dependency on other services – loosely coupled.<br />Explicit data contracts<br />A contract defines the contents of a message sent in both directions. <br />Interoperability<br />Ability to work with any platform, including non-windows.<br />Service broker is exposed to other clients through XML web services. Even Java clients can interact with Service broker.<br />
  5. 5. 5<br />What is SODA? <br />SODA – Service Oriented DATABASE Architecture<br />Natively implementing messages (data) inside the database.<br />To implement SODA, SQL Server offers:<br />Integration into .NET (SQLCLR)<br />Query Notifications<br />Service Broker<br />XML support<br />Web Services support<br />Business functionality - with SQLCLR stored procedures<br />Message bus – with Service Broker<br />Publishing – with SQL Server Web Service support.<br />
  6. 6. What Is Service Broker?<br />6<br />
  7. 7. 7<br />What is Service Broker (SB)<br />A platform for building asynchronous, scalable database applications.<br />Three features that distinguish SSB are reliable, ordered, and asynchronous delivery of messaging.<br />Supports queuing out of the box which includes features like locking, ordering, and multithreading.<br />We can use SB with a single instance or scale out across multiple instances<br />
  8. 8. 8<br />Messaging complications solved by Service Broker (1)<br />Performance<br />With service broker, the queue is a database object and thus distributed transaction and operations are usually not needed.<br />Queue Reader Management <br />With multiple queues – like a supermarket. What happens when a new line in open? Queue balancing has a cost!<br />The Service broker way – like an airport check in. Using one queue with multiple queue readers.<br />
  9. 9. 9<br />Messaging complications solved by Service Broker (2)<br />Transaction Management<br />Determine how queue readers are coordinated against one queue. Example: An order header record and some order items records. <br />Service broker uses "Conversation Group Locking" which ensures that the same queue reader processes messages from the same conservation group.<br />Message Sequencing<br />When there are several messages, each of which depends on a previous message.<br />SB includes a sequence number with every sent message.<br />In SQL 2008, SB includes built in support for conversation priorities.<br />
  10. 10. 10<br />Messaging complications solved by Service Broker (3)<br />Message Correlation.<br />When a client sends a few messages and gets back a few responses. How can a client know which response is for which request?<br />SB associates a "Conversation ID" to each message which the client can use to correlate responses to requests.<br />Maintenance<br />With MSMQ, messages are stored in the file system and data in the database. A "sync" backup will require stopping the MSMQ while performing the backup!!!<br />With SB, when performing a database backup, you backup also the queues with the messages.Everything is IN SYNC.<br />
  11. 11. What Service Broker is NOT?<br />Not a general purpose messaging system – it only works for SQL Server.<br />Supports only transactional messaging – <br />if transactional messaging is not required this is unnecessary overhead.<br />Not just a messaging system, we can use the queuing features on a single SQL Server instance or multiple instances.<br />11<br />
  12. 12. 12<br />MS Messaging alternatives (1)<br />MSMQ – Microsoft Message Queuing.<br />Since the first version of Windows NT<br />Comes with Windows for free.<br />Not bound to a specific DB<br />Message size – up to 4MB<br />For distributed transaction – MSMQ needs touse DTC.<br />Message ordering is NOT guaranteed.<br />Message correlation – not supported.<br />Queue readers are implemented manually.<br />Synching and locking between queue readers - are implemented manually.<br />Problem with backup consistency.<br />
  13. 13. 13<br />MS Messaging alternatives (2)<br />Queued Components<br />Part of Component Object Model (COM+) infrastructure.<br />Can enqueue a user request to a COM+ app and execute it asynchronously.<br />Internally- it uses MSMQ to enqueue the message.<br />On the server side, a component named "listener" is used to dequeue the message and calls the specified COM+ object.<br />Used in projects that already uses the COM+ infrastructure.<br />
  14. 14. 14<br />MS Messaging alternatives (3)<br />BizTalk is a Microsoft product for Business Process Management (BPM).<br />Enables to automate, orchestrate and optimize business processes.<br />Includes tools for design, develop, deploy, and manage those processes.<br />BizTalk can also manipulate the contents of messages over multiple transports, map message formats, manage workflows etc.<br />Uses its own messaging for Enterprise Application Integration (EAI).<br />High licensing cost (especially where scale out is needed).<br />If your app just requires reliable messaging from one SQL Server instance to another - SSB is probably a better choice.<br />
  15. 15. 15<br />MS Messaging alternatives (4)<br />XML Web Services<br />Based upon open standards such as SOAP and WSDL.<br />Since .NET 1.0 - full support for creation of web services.<br />Easy to design, implement, publish and reuse.<br />No native queuing.<br />
  16. 16. 16<br />MS Messaging alternatives (5)<br />WCF =<br />Windows Communication Foundation<br />Since .NET 3.0.<br />Based on standards.<br />Provides the same API across different communication technologies.<br />The WCF API enables to write apps in a communication-independent way.<br />No native queuing.<br />We can combine SB and WCF in applications.<br />
  17. 17. 17<br />Service Broker Basics<br />
  18. 18. 18<br />Conversation<br />A conversation is a reliable, ordered exchange of messages between two SB services.<br />Dialog – 2 way conversation between exactly two SB services<br />Service 1 = Initiator service<br />Service 2 = Target service<br />Monologue – A one way conversation between a single publisher service and several subscriber services. It's a version of "publish-subscribe" paradigm.<br />Only Dialogs are supported in SQL Server 2005/8. <br />
  19. 19. 19<br />Dialog<br />Guaranteed delivery – even if the receiver is currently offline.<br />Long lived – From a few seconds to several years.<br />Exactly once – No need to resend messages.<br />In order delivery – SB ensures the messages are received in the same order.<br />Persistence – Survives restarts of the DB server.<br />Dialog lifetime:<br />Each participant can end the conversation<br />The Initiator can optionally specify a maximum lifetime for the dialog expiration). Both participants will track the lifetime.<br />Conversations never live beyond their maximum lifetime (if specified).<br />
  20. 20. 20<br />Conversation Groups<br />Identifies one or more related conversations.<br />Allow the SB to coordinate conversations involved in a specific task.<br />A conversation can belong to one group only (one-to-many).<br />Conversation Group Lock - When a message is initiated, SB locks the conversation group. Only one session at a time can receive message of the conversation group.<br />Example: Books ordering on the internet:<br />Credit card validation.<br />Inventory service<br />Accounting service<br />Shipping service.<br />
  21. 21. 21<br />Conversation Groups<br />
  22. 22. 22<br />Message sequencing<br />Each message in the conversation gets a sequence number starting at #1.<br />The target tries to dequeue message #1, then #2 and so on.<br />When a message is lost during the sending process, the target waits until the message is successfully re-sent.<br />Reliable Delivery across the network<br />Resending and acknowledgement is built in SB.<br />
  23. 23. 23<br />Service<br />A SB Service is a named endpoint to which messages from other services are sent. A SB service is a SQL Server object<br />The interface is defined through the messages.<br />Services contain the logic (code) and the state (data)<br />Services communicate through conversions.<br />Services are mapped to queues. Messages send to a service are stored in its associated queue.<br />Each SB service consist of 4 DB objects:<br />Message types<br />Contracts<br />Queue<br />Service program<br />The first three are DB objects. <br />The Service program can be implemented:<br />Internally – as a stored procedure.<br />Externally – as a separate application.<br />
  24. 24. 24<br />
  25. 25. 25<br />Services deployment<br />On the same SQL Server DB<br />On the same SQL instance but on separate DBs.<br />On different SQL instances and on separate DBs – on a different DB Servers.<br />The services location is transparent during the development.<br />
  26. 26. 26<br />ואחרי כל ההקדמה התיאורית <br />הגיע זמן לקצת "תכל'ס"<br />
  27. 27. 27<br />Message Types<br />Defines the type of data that a message contains.<br />Must be created in each DB that participates in a conversation<br />Can perform the following validations:<br />Optional XML validation against XML schema definition (XSD).<br />Well formed XML<br />No validation (for example: when there is binary data)<br />Empty (the message body MUST be empty).<br />NOTE: XML validations can impact the overall performance (due to parsing).<br />Recommended for developing and testing only.<br />
  28. 28. 28<br />Message Types<br />Beware of message type conflicts.<br />It’s conventional to prefix each message type and contract with your own internet domain.<br />Use the DDL command CREATE MESSAGE TYPE. Example: <br /> CREATE MESSAGE TYPE [http://mydomain/SBMessages/RequestMessage] Validation=NONE<br />Use sys.service_message_types catalog view to get information about the defined message types.<br />To change a message type, use the command ALTER MESSAGE TYPE.<br />A [DEFAULT] message type exists in every database.<br />
  29. 29. 29<br />Contracts<br />An agreement between two SB services.<br />Defines the message types a SB service uses.<br />Service Broker ensures that only message types that are defined in the contract are processed.<br />Determines which message type is use by the initiator and which by the target (or used by both):<br />SENT BY INITIATOR<br />SENT BY TARGET<br />SENT BY ANY<br />
  30. 30. 30<br />Contracts<br />Use the DDL command: CREATE CONTRACT. Example: <br />CREATE CONTRACT <br /> [http://mydomain/SBMessages/DemoContract]<br /> ([http://mydomain/SBMessages/RequestMessage] <br /> SENT BY INITIATOR,<br /> [http://mydomain/SBMessages/RequestMessage] <br /> SENT BY TARGET)<br />Use sys.service_contracts and sys.service_contract_message_usages to get the contracts and the message types associated to each contract.<br />To change a contract – use DROP CONTRACT and CREATE CONTRACT again (ALTER will not work).<br />A [DEFAULT] contract exists in every database.<br />
  31. 31. 31<br />Queues<br />A queue – a storage provider for messages that are sent/received.<br />Must be defined for the initiator and for the target services.<br />When a message is sent to a target, it is enqueued in the target's queue.<br />The target service dequeues the message and processes it.<br />When the processing is done – the transaction is committed and the message is removed from the queue.<br />The queue is implemented by hidden tables. <br />Queues can be only queried for monitoring.<br />
  32. 32. 32<br />Queues<br />Use the DDL command: CREATE QUEUE. A simple example: <br />CREATE QUEUE InitiatorQueue WITH STATUS= ON<br /> CREATE QUEUE TargetQueue WITH STATUS= ON<br />Use the sys.service_queues catalog view to get information about the queues defined.<br />
  33. 33. 33<br />Service Programs<br />Service programs process incoming messages from the queue.<br />SB can activate a service program automatically when a message arrives.<br />Service programs activation can also be scheduled.<br />The Response to the initiator is a part of the message's conversation.<br />
  34. 34. 34<br />Service Programs<br />Use the DDL command CREATE SERVICE. Example:<br />CREATE SERVICE InitiatorService ON QUEUE InitiatorQueue <br /> ( [http://mydomain/SBMessages/DemoContract])<br /> CREATE SERVICE TargetService ON QUEUE TargetQueue <br /> ( [http://mydomain/SBMessages/DemoContract])<br />Use the catalog view to get information about the services defined.<br />Use the ALTER SERVICE to change the service definition. Example:<br />ALTER SERVICE TargetService ON QUEUE MyNewTagetQueue (<br /> ADD CONTRACT [MyNewContract] <br /> DROP CONTRACT [http://mydomain/SBMessages/DemoContract])<br />
  35. 35. 35<br />Sending & Receiving messages<br />Sending Message<br />In order to start the messaging, you need to:<br />Create a new conversation between 2 SB services with <br /> BEGIN DIALOG command.<br />Send a message of the required message type with <br /> SEND ON CONVERSATION command.<br />Receiving a Message<br />Use the RECEIVE command.<br />Using RECEIVE is like doing a “SELECT FROM QUEUE” command.<br />Changes the @@ROWCOUNT system variable.<br />Can be combined with WAITFOR… TIMEOUT command for a limiting the waiting time.<br />
  36. 36. 36<br />Ending a conversation<br />Use the END CONVERSATION command.<br />SB sends a message of the “built-in” message type []<br />You must explicitly end SB conversations on both service sides. If you forget to end a conversation on one side, the conversation will remain open.<br />Can use WITH CLEAN clause to remove all messages and information without notifying the other side. This is useful if the remote service has been suddenly removed.<br />
  37. 37. 37<br />Poison messages<br />A poison message is a message that will always cause the receiver to fail with its processing.<br />Example: A primary key violation.<br />A deadlock – is NOT a poison message. A retry might eventually succeed.<br />SB disables a queue that experiences 5 rollbacks in a row. It can be resolves manually or automatically with an application that subscribes to the poison message notification, using CREATE EVENT NOTIFICATION. <br />Re-enable the queue with:<br /> ALTER QUEUE <queuename> WITH STATUS = ON<br />
  38. 38. 38<br />Error Messaging (1)<br /> Use END CONVERSATION error message to send an error and end the conversation at the same time. Example:<br /> END CONVERSATION @ch <br /> WITH ERROR = 1234 DESCRIPTION = 'My error msg'<br /> The actual XML sent is:<br /><Error xmlns=""><br /> <Code>1234</Code><br /> <Description>My error message</Description><br /> </Error><br />
  39. 39. 39<br />Error Messaging (2)<br />The service that receives the error can check for an error:<br />IF (@messagetypename =<br /> '')<br /> BEGIN<br /> SET @errorcode = <br /> (SELECT @messagebody.value(<br /> N'declare namespace brokerns=<br /> "";<br /> (/brokerns:Error/brokerns:Code)[1]', 'int'));<br /> SET @errormessage = (SELECT @messagebody.value(<br /> N'declare namespace brokerns=<br /> "";<br /> (/brokerns:Error/brokerns:Description)[1]', <br /> 'nvarchar(3000)'));<br /> END<br />
  40. 40. 40<br />DEMO<br />
  41. 41. 41<br />Activation<br />Polling the queue to see if messages had arrived wastes a lot of resources when few messages are arriving on the queue.<br />Activation allows you to start a service program as soon as a new message arrives in the service queue:<br />Internal activation: For activating a stored procedure.<br />External activation: For activating an external application.<br />Parallel activation: For starting more than one stored procedure simultaneously.<br />Troubleshooting activation.<br />Activation is performed using “queue monitors” which determine how and when to activate the service.<br />
  42. 42. 42<br />Internal activation - steps<br />Configure a service queue according to your requirements <br />Create (or alter) a queue that enables activation. Example:<br />CREATE QUEUE [TargetQueue] WITH ACTIVATION (<br /> STATUS=ON, <br /> PROCEDURE_NAME = [YourServiceProcName], MAX_QUEUE_READERS=1, EXECUTE AS SELF)<br />MAX_QUEUE_READERS – maximum instances of the stored proc that the queue starts at the same time. This is actually the level of parallelism by which messages in the queue are processed.<br />EXECUTE AS – The DB account under which the activated stored proc runs. Using EXECUTE AS SELF means that the stored proc executes as the current user.<br />
  43. 43. 43<br />Activating a service on a different DB<br />The activation procedure needs to call a stored procedure on another database.<br />The activation procedure might not have sufficient privileges to call another database.<br />To fix this, you must sign the activated stored procedure with a certificate and map a user with the needed permission to this certificate.<br />Another option is to set the database as trustworthy (not recommended for production environment): <br />ALTER DATABASE <db> SET TRUSTWORTHY ON<br />
  44. 44. 44<br />Processing many queues with a single procedure<br />Create the necessary queues with the associated services.<br />Set up internal activation on each queue and point to the same procedure.<br />Write a procedure that determines which queue you’ll use to get messages from. <br />To determine from which queue has activated the procedure:<br />SELECT @queue_name = sq.[name] <br /> FROM sys.service_queues sq <br /> INNER JOIN sys.dm_broker_activated_tasks bat <br /> ON bat.spid=@@spid and <br /> sq.object_id = bat.queue_id<br />
  45. 45. 45<br />DEMO<br />
  46. 46. 46<br />External Activation<br />External activation activates all kinds of windows applications (console apps, windows services, win forms etc).<br />Internal activation is not recommended for long-duration work inside a stored procedure.<br />External activation uses SQL Server event notification mechanism.<br />Use CREATE EVENT NOTIFICATION command.<br />
  47. 47. Why use event notification<br />Needed for external service that should be activated by more than one queue<br />47<br />
  48. 48. 48<br />External Activation – Steps example<br />CREATE QUEUE ExternalActivatorQueue<br />CREATE SERVICE ExternalActivatorService ON ExternalActivatorQueue (<br /> [<br /> /PostEventNotification] )<br />CREATE EVENT NOTIFICATION EventNotifTargetQueue<br /> ON QUEUE TargetQueue <br /> FOR QUEUE_ACTIVATION<br /> TO SERVICE 'ExternalActivatorService', <br /> 'current database'<br />
  49. 49. 49<br />Using managed code<br />Use the ServiceBrokerInterface solution that can be found in the samples directory of SQL Server 2008<br />Contains classes such as Conversation, Message, Service.<br />You can build a service class derived from the class “Service”.<br />c#<br />
  50. 50. 50<br />DEMO<br />
  51. 51. 51<br />Conversation Groups<br />Ensures ordered message processing and supports synchronization support for multiple queue readers.<br />Multiple queue readers can gain SCALABILITY.<br />Ensures that only one task can read messages from a particular conversation at the same time.<br />Every conversation belongs to a conversation group.<br />A conversation group can contain one or more conversations.<br />Use the WITH RELATED_CONVERSATION clause when creating a new dialog<br />You might need to create an application state table for more complex business logic and monitoring.<br />
  52. 52. 52<br />Using Conversation Groups<br />Use the WITH RELATED_CONVERSATION clause when creating a new dialog.<br />BEGIN DIALOG @ch1<br />FROM SERVICE [InitiatorService]<br />TO SERVICE 'TargetService1'<br />WITH ENCRYPTION = OFF;<br />BEGIN DIALOG @ch2<br />FROM SERVICE [InitiatorService]<br />TO SERVICE 'TargetService2'<br />WITH RELATED_CONVERSATION = @ch1,<br />ENCRYPTION = OFF;<br />
  53. 53. Distributed Architecture<br />You’ll need to set up the following:<br />Remote Service Bindings<br />Routes<br />Service Broker Endpoints<br />53<br />
  54. 54. Remote Service Binding<br />A remote service bindingestablishes a relationship between:<br />Local database user<br />The certificate for the user<br />The name of a remote service. <br />A remote service binding specifies the identity to be used to authenticate to the remote service.<br />Use T-SQL command:<br />CREATE REMOTE SERVICE BINDING<br />54<br />
  55. 55. 55<br />Routes<br />SQL Server objects that specify on which IP a SB service is located.<br />By default, each database contains a route that specifies that messages for any service which does not have an explicit route are delivered within the SQL Server instance. <br />Enables flexible deployment.<br />Development can be on the same DB and on the same instance.<br />On production, can be on different DB servers.<br />
  56. 56. Routes<br />56<br />
  57. 57. Endpoints<br />A SB endpoint configures SQL Server to send and receive Service Broker messages over the network. <br />Endpoints are specified using service names.<br />Listens on a specific port.<br />Options for transport security and message forwarding.<br />57<br />
  58. 58. 58<br />Security<br />SB allows services to communicated even when the instances are on different machines, have no trusted relationship and on different networks.<br />2 levels of security:<br />Transport security <br />Dialog security<br />
  59. 59. Transport security <br />Windows-based authentication - using NTLM or Kerberos. Can be used only on servers of the same domain or server on different domains that are trusted.<br />Certificate-based authentication – using certificates. Usually used with services that reside on different physical networks on distrusted domains.<br />Dialog security<br />Service Broker supports "forwarders". A forwarder is a SQL Server instance that accepts service broker messages and forwards them to the next hop on the route to the target service.<br />Using a forwarder requires the decryption of the message and encrypting it again. Causes slower performance.<br />59<br />
  60. 60. Dialog security<br />Secures each individual dialog between two dialog endpoints, regardless of how many networks the messages traverse as the travel between the conversation endpoints.<br />Dialog security establishes authenticated and encrypted communication between two services.<br />Dialog security provides encryption, remote authentication, and remote authorization for a specific conversation. <br />60<br />
  61. 61. 61<br />Summary<br />Service Broker is a good choice for transactional, data processing based messaging solution.<br />Service broker database objects such as: Message types, Contracts, Queues and Services can be easily built using T-SQL.<br />SB can Handling errors and poison messages.<br />SB can maintain a logical connection between messages using conversation groups.<br />SB supports Internal activation as well as external activation.<br />SB can support distributed application architecture using routes.<br />SB can secure the messages payload with the excellent encryption algorithms SQL Server provides.<br />
  62. 62. 62<br />Thank you for listening<br />Lior King<br />Database & Infrastructure Group Manager<br />SRL Group<br />Download this presentation from my Blog: KingLior.WordPress.Com<br />My Email:<br />