SlideShare a Scribd company logo
1 of 19
Messages & Queues in SQL Server
Enhance performance by using queues in
SQL Server
Bio - Niels Berglund
 Software Specialist - Derivco
 Software Specialist - lots of production dev. plus figuring out
ways to "use and abuse" existing and new technologies






Author - "First Look at SQL Server 2005 for Developers"
Researcher / Instructor - DevelopMentor
Speaker - TechEd, DevWeek, SQL Pass, etc.
Longtime user of SQL Server

 www.derivco.com
 niels.it.berglund@gmail.com
 @nielsberglund

2 |

10/28/201
Footer Goes Here
3 |
Derivco
 World's leading development house for online
gaming software; Casino, Poker, Bingo etc.
 Offices in Durban, Cape Town, Pretoria (soon)
 Estonia, Hong Kong, Sweden, UK

 Technology company
 One of the world's largest install base of SQL Server's
(~300 SQL Server servers, multiple instances & db's).
 SQL Server 2008 / 2012, research into 2014
 Hadoop, Windows Azure
 .NET 4.5, SignalR, WebSockets, mobile (Android, iOS)

WE ARE HIRING
Disclaimer

I really, really like Service Broker!!
Honest, I Do!
Background
 In certain scenarios beneficial to off-load work to other
processes/threads.
 In SQL Server we have no real way to control threading
 Historically difficult to create messaging applications in SQL
Server, due to queuing is highly concurrent.
 how do we ensure that multiple consumers does not block each
other
 how do we de-queue without causing deadlocks
 etc.

 SQL Server 2005 introduced new functionality which makes
it easier to remove a de-queued row and return it to the
caller in one atomic statement:
 DELETE TOP(x)
 OUTPUT statement
De-queuing old vs. new
--old way
DECLARE @tab TABLE(RowID bigint, MsgTypeID int, Msg varchar(500),
EnqueueDate datetime2)
INSERT INTO @tab
SELECT TOP (1) * FROM dbo.tb_QueueTabClIdx WITH(UPDLOCK, READPAST)
DELETE clix FROM dbo.tb_QueueTabClIdx clix
JOIN @tab t ON clix.RowID = t.RowID

--new way
DECLARE @tab TABLE(RowID bigint, MsgTypeID int, Msg varchar(500),
EnqueueDate datetime2)
DELETE TOP(1) dbo.tb_QueueTabClIdx WITH(ROWLOCK, READPAST)
OUTPUT deleted.RowID, deleted.MsgTypeID, deleted.Msg, deleted.EnqueueDate
INTO @tab(RowID, MsgTypeID, Msg, EnqueueDate)
Queue types
 Heap queue






backed by heap table
heap table is a table with no clustered index
cannot guarantee order of en-queue, de-queue
useful for specific queuing scenarios
beware of side effects (data growth)

 Ordered queue (FIFO, LIFO)
 First In First Out, Last In First Out
 in LIFO queues beware of hot-spots (inserting, deleting same group of
rows)
 backed by table with clustered index (can be non-unique or unique)
 de-queuing has to be done with an ORDER BY clause

 SQL Server Service Broker Queue (SSB Queue)
 Bound queues (more later)
De-queuing ordered queues
 De-queue has to be done with an ORDER BY clause
 Unfortunately DELETE does not support ORDER BY 
 By using a CTE we can however do it in a very efficient way
 the query will execute as a DELETE,
 NOT SELECT followed by DELETE, nor as SELECT in context
of a DELETE
 SELECT automatically taking UPDATE lock
;WITH delCte
AS
(
SELECT TOP(1) RowID, Msg, EnqueueDate
FROM dbo.tb_QueueTabClIdx WITH(ROWLOCK, READPAST)
ORDER BY RowId
)
DELETE delCte
OUTPUT deleted.*
SSB queues
 SSB allows internal or external processes to send
and receive guaranteed, asynchronous messages
by using extensions to DML
 It has the concept of queues, meant for use by SSB
 When using it in a "normal" queuing application, it
has several short-comings:
 convoluted way to en-queue messages
 rigid structure
 performance

 One big plus though: Activation
 stored procedure that automatically is activated when a
message is en-queued on the SSB queue.
 can control concurrency
Performance I
 Multiple producers running concurrently
 One consumer running in parallel
 Each producer en-queuing one record
 running in a tight loop, 10,000 times

 Consumer started together with the
producers, de-queuing until no more data.
Bound queues
 High volume inserts/deletes causes problems in
a db:
 heap table unlimited growth
 statistics are never up to date
 auto updates of statistics constantly kicking in,
creating jagged CPU patterns and throughput
 new pages constantly allocated, de-allocated stresses internal allocation structures

 Quite a few high performing queuing
applications are using a bound queue in a ringbuffer scenario
 minimizes memory allocation, de-allocation
Table backing ring-buffer
CREATE TABLE dbo.tb_QueueTabRingBuffer
(
MsgSlot BIGINT NOT NULL
, MessageID BIGINT NULL
, MsgTypeID int NULL
, EnqueueDate datetime2 NOT NULL
, Msg char(500) NOT NULL
, ReferenceCount TINYINT NOT NULL
)
Using a ring-buffer like table
 After creation of table, prefill with data (keep track of how
many rows inserted)
 To enqueue:
 create a new message id
 find the next available slot
 update the message column and add one to the reference count

 To de-queue
 find the smallest message id that has not yet been de-queued.
 read and return the message column
 decrement reference count, marking the slot as available.

 We need to be able to extremely efficiently locate the next
available slot
 For this we use a sequence object
Sequence object
 A high scale data structure to generate "next number"
 quite a few "neat" features

 Introduced in SQL Server 2012
 When used in conjunction with the modulo operator (%)
we can efficiently get next slot etc.
CREATE SEQUENCE dbo.seq_Test AS BIGINT
START WITH 1 INCREMENT BY 1
CACHE 5000;
GO
SELECT NEXT VALUE FOR dbo.seq_Test;
En-queuing
 When en-queuing into a ring-buffer, the en-queue may
block if no available slots.
 Need to handle that in en-queue code (not shown below)
DECLARE
DECLARE
DECLARE
DECLARE

@enqueuSequence bigint;
@slot int;
@QueueSize int = 5000;
@msg char(500) = 'this is a new message';

--grab the next value, and slot
SET @enqueuSequence = NEXT VALUE FOR dbo.seq_Enqueue;
SET @Slot = @enqueuSequence % @QueueSize
--do the update
UPDATE dbo.tb_QueueTabRingBuffer WITH(ROWLOCK)
SET EnqueueDate = SYSDATETIME(), Msg = @Msg, MessageID =
@enqueuSequence, MsgTypeID = 2, ReferenceCount = 1
WHERE MsgSlot = @Slot AND ReferenceCount = 0
De-queuing
 De-queuing is similar to en-queue. Need however to
ensure that the de-queue sequence does not out of
synch with the en-queue.
DECLARE @dequeuSequence bigint;
DECLARE @slot int;
DECLARE @queueSize int = 5000;
--grab the next MessageID, and slot
SET @dequeuSequence = NEXT VALUE FOR dbo.seq_Dequeue;
SET @Slot = @dequeuSequence % @QueueSize
UPDATE dbo.tb_QueueTabRingBuffer WITH(ROWLOCK)
SET EnqueueDate = SYSDATETIME(), MessageID = NULL, MsgTypeID = NULL
, Msg = 'dummy', ReferenceCount = 0
OUTPUT deleted.*
WHERE MsgSlot = @Slot AND MessageID = @dequeuSequence
AND ReferenceCount = 1;
Summary
 Implementing efficient queuing in SQL Server is definitely
doable
 SQL Server 2008R2
 the best table structure for overall performance is a queue
backed by clustered non-unique index
 for certain specialized scenarios a heap-table can come into play
(beware of data growth)

 SQL Server 2012
 a ring-buffer like structure using sequence objects are the
absolutely best performing table structure
 beware of more convoluted code to keep the en-queue and dequeue in synch

 SQL Server Service Broker
 too convoluted, not enough performance 
 activation procedures its strong point

More Related Content

What's hot

Faster transactions & analytics with the new SQL2016 In-memory technologies
Faster transactions & analytics with the new SQL2016 In-memory technologiesFaster transactions & analytics with the new SQL2016 In-memory technologies
Faster transactions & analytics with the new SQL2016 In-memory technologiesHenk van der Valk
 
Introduction to data.table in R
Introduction to data.table in RIntroduction to data.table in R
Introduction to data.table in RPaul Richards
 
Accelerating Local Search with PostgreSQL (KNN-Search)
Accelerating Local Search with PostgreSQL (KNN-Search)Accelerating Local Search with PostgreSQL (KNN-Search)
Accelerating Local Search with PostgreSQL (KNN-Search)Jonathan Katz
 
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스PgDay.Seoul
 
Understanding Query Execution
Understanding Query ExecutionUnderstanding Query Execution
Understanding Query Executionwebhostingguy
 
Andrew Dunstan 9.3 JSON Presentation @ Postgres Open 2013
Andrew Dunstan 9.3 JSON Presentation @ Postgres Open 2013Andrew Dunstan 9.3 JSON Presentation @ Postgres Open 2013
Andrew Dunstan 9.3 JSON Presentation @ Postgres Open 2013PostgresOpen
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applicationsSkills Matter
 
Tech Talk: Best Practices for Data Modeling
Tech Talk: Best Practices for Data ModelingTech Talk: Best Practices for Data Modeling
Tech Talk: Best Practices for Data ModelingScyllaDB
 
Diagnosing Open-Source Community Health with Spark-(William Benton, Red Hat)
Diagnosing Open-Source Community Health with Spark-(William Benton, Red Hat)Diagnosing Open-Source Community Health with Spark-(William Benton, Red Hat)
Diagnosing Open-Source Community Health with Spark-(William Benton, Red Hat)Spark Summit
 
Python and Data Analysis
Python and Data AnalysisPython and Data Analysis
Python and Data AnalysisPraveen Nair
 
PHP Machinist Presentation
PHP Machinist PresentationPHP Machinist Presentation
PHP Machinist PresentationAdam Englander
 
3. basic data structures(2)
3. basic data structures(2)3. basic data structures(2)
3. basic data structures(2)Hongjun Jang
 
Store and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and CassandraStore and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and CassandraDeependra Ariyadewa
 
Introduction To MySQL Lecture 1
Introduction To MySQL Lecture 1Introduction To MySQL Lecture 1
Introduction To MySQL Lecture 1Ajay Khatri
 
15 MySQL Basics #burningkeyboards
15 MySQL Basics #burningkeyboards15 MySQL Basics #burningkeyboards
15 MySQL Basics #burningkeyboardsDenis Ristic
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationNaveen Gupta
 

What's hot (20)

Faster transactions & analytics with the new SQL2016 In-memory technologies
Faster transactions & analytics with the new SQL2016 In-memory technologiesFaster transactions & analytics with the new SQL2016 In-memory technologies
Faster transactions & analytics with the new SQL2016 In-memory technologies
 
Introduction to data.table in R
Introduction to data.table in RIntroduction to data.table in R
Introduction to data.table in R
 
Accelerating Local Search with PostgreSQL (KNN-Search)
Accelerating Local Search with PostgreSQL (KNN-Search)Accelerating Local Search with PostgreSQL (KNN-Search)
Accelerating Local Search with PostgreSQL (KNN-Search)
 
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스
 
Understanding Query Execution
Understanding Query ExecutionUnderstanding Query Execution
Understanding Query Execution
 
MongoDB-SESSION03
MongoDB-SESSION03MongoDB-SESSION03
MongoDB-SESSION03
 
Andrew Dunstan 9.3 JSON Presentation @ Postgres Open 2013
Andrew Dunstan 9.3 JSON Presentation @ Postgres Open 2013Andrew Dunstan 9.3 JSON Presentation @ Postgres Open 2013
Andrew Dunstan 9.3 JSON Presentation @ Postgres Open 2013
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applications
 
Tech Talk: Best Practices for Data Modeling
Tech Talk: Best Practices for Data ModelingTech Talk: Best Practices for Data Modeling
Tech Talk: Best Practices for Data Modeling
 
Diagnosing Open-Source Community Health with Spark-(William Benton, Red Hat)
Diagnosing Open-Source Community Health with Spark-(William Benton, Red Hat)Diagnosing Open-Source Community Health with Spark-(William Benton, Red Hat)
Diagnosing Open-Source Community Health with Spark-(William Benton, Red Hat)
 
Dplyr and Plyr
Dplyr and PlyrDplyr and Plyr
Dplyr and Plyr
 
Python and Data Analysis
Python and Data AnalysisPython and Data Analysis
Python and Data Analysis
 
PHP Machinist Presentation
PHP Machinist PresentationPHP Machinist Presentation
PHP Machinist Presentation
 
3. basic data structures(2)
3. basic data structures(2)3. basic data structures(2)
3. basic data structures(2)
 
Store and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and CassandraStore and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and Cassandra
 
Introduction To MySQL Lecture 1
Introduction To MySQL Lecture 1Introduction To MySQL Lecture 1
Introduction To MySQL Lecture 1
 
15 MySQL Basics #burningkeyboards
15 MySQL Basics #burningkeyboards15 MySQL Basics #burningkeyboards
15 MySQL Basics #burningkeyboards
 
MySQL vs. PostgreSQL
MySQL vs. PostgreSQLMySQL vs. PostgreSQL
MySQL vs. PostgreSQL
 
Oracle PL-SQL
Oracle PL-SQLOracle PL-SQL
Oracle PL-SQL
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 

Similar to Queuing Sql Server: Utilise queues to increase performance in SQL Server

Changing your huge table's data types in production
Changing your huge table's data types in productionChanging your huge table's data types in production
Changing your huge table's data types in productionJimmy Angelakos
 
Performance improvements in PostgreSQL 9.5 and beyond
Performance improvements in PostgreSQL 9.5 and beyondPerformance improvements in PostgreSQL 9.5 and beyond
Performance improvements in PostgreSQL 9.5 and beyondTomas Vondra
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select TopicsJay Coskey
 
ClickHouse new features and development roadmap, by Aleksei Milovidov
ClickHouse new features and development roadmap, by Aleksei MilovidovClickHouse new features and development roadmap, by Aleksei Milovidov
ClickHouse new features and development roadmap, by Aleksei MilovidovAltinity Ltd
 
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1MariaDB plc
 
What's New for Developers in SQL Server 2008?
What's New for Developers in SQL Server 2008?What's New for Developers in SQL Server 2008?
What's New for Developers in SQL Server 2008?ukdpe
 
SQL Server 2008 Overview
SQL Server 2008 OverviewSQL Server 2008 Overview
SQL Server 2008 OverviewEric Nelson
 
Sorry - How Bieber broke Google Cloud at Spotify
Sorry - How Bieber broke Google Cloud at SpotifySorry - How Bieber broke Google Cloud at Spotify
Sorry - How Bieber broke Google Cloud at SpotifyNeville Li
 
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1MariaDB plc
 
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1MariaDB plc
 
Database Performance Tuning
Database Performance Tuning Database Performance Tuning
Database Performance Tuning Arno Huetter
 
Use Your MySQL Knowledge to Become an Instant Cassandra Guru
Use Your MySQL Knowledge to Become an Instant Cassandra GuruUse Your MySQL Knowledge to Become an Instant Cassandra Guru
Use Your MySQL Knowledge to Become an Instant Cassandra GuruTim Callaghan
 
dbs class 7.ppt
dbs class 7.pptdbs class 7.ppt
dbs class 7.pptMARasheed3
 
Postgres can do THAT?
Postgres can do THAT?Postgres can do THAT?
Postgres can do THAT?alexbrasetvik
 
10 Reasons to Start Your Analytics Project with PostgreSQL
10 Reasons to Start Your Analytics Project with PostgreSQL10 Reasons to Start Your Analytics Project with PostgreSQL
10 Reasons to Start Your Analytics Project with PostgreSQLSatoshi Nagayasu
 
MySQL 8.0 New Features -- September 27th presentation for Open Source Summit
MySQL 8.0 New Features -- September 27th presentation for Open Source SummitMySQL 8.0 New Features -- September 27th presentation for Open Source Summit
MySQL 8.0 New Features -- September 27th presentation for Open Source SummitDave Stokes
 
Maryna Popova "Deep dive AWS Redshift"
Maryna Popova "Deep dive AWS Redshift"Maryna Popova "Deep dive AWS Redshift"
Maryna Popova "Deep dive AWS Redshift"Lviv Startup Club
 
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...NoSQLmatters
 

Similar to Queuing Sql Server: Utilise queues to increase performance in SQL Server (20)

Changing your huge table's data types in production
Changing your huge table's data types in productionChanging your huge table's data types in production
Changing your huge table's data types in production
 
Performance improvements in PostgreSQL 9.5 and beyond
Performance improvements in PostgreSQL 9.5 and beyondPerformance improvements in PostgreSQL 9.5 and beyond
Performance improvements in PostgreSQL 9.5 and beyond
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select Topics
 
ClickHouse new features and development roadmap, by Aleksei Milovidov
ClickHouse new features and development roadmap, by Aleksei MilovidovClickHouse new features and development roadmap, by Aleksei Milovidov
ClickHouse new features and development roadmap, by Aleksei Milovidov
 
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
 
What's New for Developers in SQL Server 2008?
What's New for Developers in SQL Server 2008?What's New for Developers in SQL Server 2008?
What's New for Developers in SQL Server 2008?
 
SQL Server 2008 Overview
SQL Server 2008 OverviewSQL Server 2008 Overview
SQL Server 2008 Overview
 
Sorry - How Bieber broke Google Cloud at Spotify
Sorry - How Bieber broke Google Cloud at SpotifySorry - How Bieber broke Google Cloud at Spotify
Sorry - How Bieber broke Google Cloud at Spotify
 
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
 
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
 
Database Performance Tuning
Database Performance Tuning Database Performance Tuning
Database Performance Tuning
 
Use Your MySQL Knowledge to Become an Instant Cassandra Guru
Use Your MySQL Knowledge to Become an Instant Cassandra GuruUse Your MySQL Knowledge to Become an Instant Cassandra Guru
Use Your MySQL Knowledge to Become an Instant Cassandra Guru
 
dbs class 7.ppt
dbs class 7.pptdbs class 7.ppt
dbs class 7.ppt
 
Triggers and Stored Procedures
Triggers and Stored ProceduresTriggers and Stored Procedures
Triggers and Stored Procedures
 
Oracle NOLOGGING
Oracle NOLOGGINGOracle NOLOGGING
Oracle NOLOGGING
 
Postgres can do THAT?
Postgres can do THAT?Postgres can do THAT?
Postgres can do THAT?
 
10 Reasons to Start Your Analytics Project with PostgreSQL
10 Reasons to Start Your Analytics Project with PostgreSQL10 Reasons to Start Your Analytics Project with PostgreSQL
10 Reasons to Start Your Analytics Project with PostgreSQL
 
MySQL 8.0 New Features -- September 27th presentation for Open Source Summit
MySQL 8.0 New Features -- September 27th presentation for Open Source SummitMySQL 8.0 New Features -- September 27th presentation for Open Source Summit
MySQL 8.0 New Features -- September 27th presentation for Open Source Summit
 
Maryna Popova "Deep dive AWS Redshift"
Maryna Popova "Deep dive AWS Redshift"Maryna Popova "Deep dive AWS Redshift"
Maryna Popova "Deep dive AWS Redshift"
 
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
 

Recently uploaded

SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 

Recently uploaded (20)

SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 

Queuing Sql Server: Utilise queues to increase performance in SQL Server

  • 1. Messages & Queues in SQL Server Enhance performance by using queues in SQL Server
  • 2. Bio - Niels Berglund  Software Specialist - Derivco  Software Specialist - lots of production dev. plus figuring out ways to "use and abuse" existing and new technologies     Author - "First Look at SQL Server 2005 for Developers" Researcher / Instructor - DevelopMentor Speaker - TechEd, DevWeek, SQL Pass, etc. Longtime user of SQL Server  www.derivco.com  niels.it.berglund@gmail.com  @nielsberglund 2 | 10/28/201 Footer Goes Here 3 |
  • 3. Derivco  World's leading development house for online gaming software; Casino, Poker, Bingo etc.  Offices in Durban, Cape Town, Pretoria (soon)  Estonia, Hong Kong, Sweden, UK  Technology company  One of the world's largest install base of SQL Server's (~300 SQL Server servers, multiple instances & db's).  SQL Server 2008 / 2012, research into 2014  Hadoop, Windows Azure  .NET 4.5, SignalR, WebSockets, mobile (Android, iOS) WE ARE HIRING
  • 4. Disclaimer I really, really like Service Broker!! Honest, I Do!
  • 5. Background  In certain scenarios beneficial to off-load work to other processes/threads.  In SQL Server we have no real way to control threading  Historically difficult to create messaging applications in SQL Server, due to queuing is highly concurrent.  how do we ensure that multiple consumers does not block each other  how do we de-queue without causing deadlocks  etc.  SQL Server 2005 introduced new functionality which makes it easier to remove a de-queued row and return it to the caller in one atomic statement:  DELETE TOP(x)  OUTPUT statement
  • 6. De-queuing old vs. new --old way DECLARE @tab TABLE(RowID bigint, MsgTypeID int, Msg varchar(500), EnqueueDate datetime2) INSERT INTO @tab SELECT TOP (1) * FROM dbo.tb_QueueTabClIdx WITH(UPDLOCK, READPAST) DELETE clix FROM dbo.tb_QueueTabClIdx clix JOIN @tab t ON clix.RowID = t.RowID --new way DECLARE @tab TABLE(RowID bigint, MsgTypeID int, Msg varchar(500), EnqueueDate datetime2) DELETE TOP(1) dbo.tb_QueueTabClIdx WITH(ROWLOCK, READPAST) OUTPUT deleted.RowID, deleted.MsgTypeID, deleted.Msg, deleted.EnqueueDate INTO @tab(RowID, MsgTypeID, Msg, EnqueueDate)
  • 7. Queue types  Heap queue      backed by heap table heap table is a table with no clustered index cannot guarantee order of en-queue, de-queue useful for specific queuing scenarios beware of side effects (data growth)  Ordered queue (FIFO, LIFO)  First In First Out, Last In First Out  in LIFO queues beware of hot-spots (inserting, deleting same group of rows)  backed by table with clustered index (can be non-unique or unique)  de-queuing has to be done with an ORDER BY clause  SQL Server Service Broker Queue (SSB Queue)  Bound queues (more later)
  • 8. De-queuing ordered queues  De-queue has to be done with an ORDER BY clause  Unfortunately DELETE does not support ORDER BY   By using a CTE we can however do it in a very efficient way  the query will execute as a DELETE,  NOT SELECT followed by DELETE, nor as SELECT in context of a DELETE  SELECT automatically taking UPDATE lock ;WITH delCte AS ( SELECT TOP(1) RowID, Msg, EnqueueDate FROM dbo.tb_QueueTabClIdx WITH(ROWLOCK, READPAST) ORDER BY RowId ) DELETE delCte OUTPUT deleted.*
  • 9. SSB queues  SSB allows internal or external processes to send and receive guaranteed, asynchronous messages by using extensions to DML  It has the concept of queues, meant for use by SSB  When using it in a "normal" queuing application, it has several short-comings:  convoluted way to en-queue messages  rigid structure  performance  One big plus though: Activation  stored procedure that automatically is activated when a message is en-queued on the SSB queue.  can control concurrency
  • 10. Performance I  Multiple producers running concurrently  One consumer running in parallel  Each producer en-queuing one record  running in a tight loop, 10,000 times  Consumer started together with the producers, de-queuing until no more data.
  • 11.
  • 12. Bound queues  High volume inserts/deletes causes problems in a db:  heap table unlimited growth  statistics are never up to date  auto updates of statistics constantly kicking in, creating jagged CPU patterns and throughput  new pages constantly allocated, de-allocated stresses internal allocation structures  Quite a few high performing queuing applications are using a bound queue in a ringbuffer scenario  minimizes memory allocation, de-allocation
  • 13. Table backing ring-buffer CREATE TABLE dbo.tb_QueueTabRingBuffer ( MsgSlot BIGINT NOT NULL , MessageID BIGINT NULL , MsgTypeID int NULL , EnqueueDate datetime2 NOT NULL , Msg char(500) NOT NULL , ReferenceCount TINYINT NOT NULL )
  • 14. Using a ring-buffer like table  After creation of table, prefill with data (keep track of how many rows inserted)  To enqueue:  create a new message id  find the next available slot  update the message column and add one to the reference count  To de-queue  find the smallest message id that has not yet been de-queued.  read and return the message column  decrement reference count, marking the slot as available.  We need to be able to extremely efficiently locate the next available slot  For this we use a sequence object
  • 15. Sequence object  A high scale data structure to generate "next number"  quite a few "neat" features  Introduced in SQL Server 2012  When used in conjunction with the modulo operator (%) we can efficiently get next slot etc. CREATE SEQUENCE dbo.seq_Test AS BIGINT START WITH 1 INCREMENT BY 1 CACHE 5000; GO SELECT NEXT VALUE FOR dbo.seq_Test;
  • 16. En-queuing  When en-queuing into a ring-buffer, the en-queue may block if no available slots.  Need to handle that in en-queue code (not shown below) DECLARE DECLARE DECLARE DECLARE @enqueuSequence bigint; @slot int; @QueueSize int = 5000; @msg char(500) = 'this is a new message'; --grab the next value, and slot SET @enqueuSequence = NEXT VALUE FOR dbo.seq_Enqueue; SET @Slot = @enqueuSequence % @QueueSize --do the update UPDATE dbo.tb_QueueTabRingBuffer WITH(ROWLOCK) SET EnqueueDate = SYSDATETIME(), Msg = @Msg, MessageID = @enqueuSequence, MsgTypeID = 2, ReferenceCount = 1 WHERE MsgSlot = @Slot AND ReferenceCount = 0
  • 17. De-queuing  De-queuing is similar to en-queue. Need however to ensure that the de-queue sequence does not out of synch with the en-queue. DECLARE @dequeuSequence bigint; DECLARE @slot int; DECLARE @queueSize int = 5000; --grab the next MessageID, and slot SET @dequeuSequence = NEXT VALUE FOR dbo.seq_Dequeue; SET @Slot = @dequeuSequence % @QueueSize UPDATE dbo.tb_QueueTabRingBuffer WITH(ROWLOCK) SET EnqueueDate = SYSDATETIME(), MessageID = NULL, MsgTypeID = NULL , Msg = 'dummy', ReferenceCount = 0 OUTPUT deleted.* WHERE MsgSlot = @Slot AND MessageID = @dequeuSequence AND ReferenceCount = 1;
  • 18.
  • 19. Summary  Implementing efficient queuing in SQL Server is definitely doable  SQL Server 2008R2  the best table structure for overall performance is a queue backed by clustered non-unique index  for certain specialized scenarios a heap-table can come into play (beware of data growth)  SQL Server 2012  a ring-buffer like structure using sequence objects are the absolutely best performing table structure  beware of more convoluted code to keep the en-queue and dequeue in synch  SQL Server Service Broker  too convoluted, not enough performance   activation procedures its strong point

Editor's Notes

  1. Do not take any notice of the absolute numbers - the tests run on a low-end machine, in a VM. Look at the relations between the various structures.
  2. Do not take any notice of the absolute numbers - the tests run on a low-end machine, in a VM. Look at the relations between the various structures.