Friday, 31 May 2013

The database isn't your performance bottleneck

Quite often as a data professional you will hear that the database is the bottleneck although there isn't really much backing up why other than people's experience. I suspect that this is most likely that their experience has been a poor one and that it's a general thought without really understanding why they say this.

For my part, I'd normally quite happily say that the opposite can be true, but lets give it a little more substance if I can.

Databases are generally misunderstood and even more dangerously, people 'think' they understand them. If you look in terms of performance you find there are some areas that time is spent/lost and these are :


  • Logging (a transaction log)
  • Latching (for the most part this happens when loading data into memory)
  • Locking (locking the data so it can be altered)
  • B-Tree maintenance (indexes)
  • Querying the data (yes, this is where joins come into it if using an RDBMS)

When you add in high concurrency you effectively complicate this as the database has a much smaller window (that decreases as you add users) to operate in. Plus all 5 are mixed in together.

The more data you need to work with, the more thought you need to put in. My current systems have approx 2 billion rows across all tables. My previous employers had individual tables with 17 billion rows in (a 1.5TB table). 

The easiest ways of giving yourself a bigger window is to add memory and speed up your IO responsiveness. NAND flash negates the latency found with mechanical storage so some previous worries can be pushed further away. This is easy stuff for a DBA to do as it doesn't involve the development teams and gives quick and easy wins with minimum effort (there is a hell of a lot more that goes on in case you were wondering). Once you have done this you take care of most of the issues mentioned above. However, this leaves querying.....

As a general rule, people write bad queries (and this includes seasoned data professionals). It's not that they mean to, it's just that you can write the same query in dozens of ways and the speed will vary a lot. You don't get told what's good or what's bad and can generally get your data back regardless. Until you see this under load you won't be aware of how this manifests in live. This is the problem. You likely haven't actually seen that the problem exists already and it won't rear its head until it's under load. What makes this problem a hundred times worse is that when identified, there is little willingness to make a simple change and improve it. Rinse and repeat and you have a mess.

For this reason, DBA's will want to be able to get to the offending query (hence preferring stored procs as they won't get to the code). If they can tweak the query, they can improve the system. If they can't, they have to find a willing product owner, dev lead or whatever you want to call them. Time has to be found and testing re-done and so on. If it was right early on before shipping it saves time and money.

A DB developer should be able to help tune the queries but sadly this is often looked at as 'micro-optimisation'. It's not really fair that they are held back from applying their experience but are then beaten with the stick that has 'bottleneck' written on it.

An ORM can help save a lot of development time, but you really should think about how many times that query is run and how much cost there is to support that for several years. Personally I'd suggest the ORM should be used to speed up development but then write the query properly when it needs to be done. Don't just stick to one rule or the other, find the balance.

A lot of teams do TDD (Test Driven Development) and if they don't, they should. Maybe I should push people towards Load Test Driven Development ?

If you have a large number of people using your system you really do need to go beyond functional testing, but also put a lot of effort into load testing. This isn't something that necessarily refers only to the data tier, but throughout the stack. You may perceive that a query functions fine as it passes your tests. Well, being blunt, that's a bit boring in the high concurrency game. How does it function with 100 users, 1,000 users ? 10,000 ? And so on.....

Those problems that you didn't know you have will rise to the surface and then you have a bottleneck. You fix this by solving the IO, memory, code, and scale out your hardware to suit. It won't address the underlying issues though.

Don't start thinking you are Facebook or Twitter and use what they use to solve much bigger concerns. Just get the little bits right. It will make the world of difference. When you find a problem, fix it and move on. Don't find it, flag it and then do fuck all about it.

Your end game is to ultimately solve latency throughout the stack. The less things that get in the way, the faster you can go. The better you can do this, the less kit you need (you do need some, but likely much less than you think).

To leave with a thought, just because it passes a functional test and the syntax parses does not mean it is fit for a live estate. The detail is important most of the time.


Thursday, 16 May 2013

Joins are bad aren't they ?

First up, I'm going to make a fairly large assumption in that you probably don't realise what you are asking of your data.

Imagine you have a book and I ask you for some information from it. If you don't know exactly what is being asked you are going to have to read the entire book from start to finish. Welcome to the term 'table scan'. Your book is your table and you read everything in order to get a small snippet of information.

Reading this book will take some time but a computerised version means you might not notice this duration as it can still be perceived as fast enough (a good data professional will look to negate this time spent).

If I tell you what chapter, page, line and word I'm after then you can flick through that book very quickly without having to bother reading the rest of the book. This is what a 'clustered index' is.

If your book was effectively an encyclopaedia then you don't want to pick up the entire series of books. This is what 'vertical partitioning' is (choosing the book we want and not picking up the other books) 

So, now lets go and get a second book.

Now I'm going to ask for something from Book A and also something from Book B and from the two I'll put this information together into something I want.

So, if I read Line 1 of Page 1 of Book A then read the entirety of Book B before reading Line 2 of Page 1 of Book A, then read the entirety of Book B again until we have reached the end of Book A then you will soon see that this is going to take a long time. 

Add in lots more books and it gets worse and worse. If I did a calculation every time I read a new line in Book A then this is what happens when you put calculations in your 'WHERE clause'. If I did this for Book B, this means that same calculation gets run a hell of a lot as we read this entire book multiple times and do this calculation each time we read a line in Book B. To understand this better you should have a look at 'Cartesian Products' as that is what you are asking for. If TableA has 10 rows and TableB also has 10 rows, with a Cartesian Product you will get back 10x10 (which is 100 as you should well know).

This is effectively why people state 'joins are bad'. In reality, it should be 'doing something stupid is bad'.

What I need to aim for is to find what I want from Book A very quickly and then what I want from Book B without reading both books multiple times. I can do this by getting my indexing right so that I cut out the data that I'm not interested in. I can simply find what I want from Book A by navigating the index to the Chapter, Page, Line and Word and then doing the same with Book B.

Now, stepping into indexes a little, if the index was the clustered index, this is the word that we want to get from each book. If it was a non-clustered index this is pretty much like first looking in the book's index and then finding the page and line to go and look up the word we want.

It really is that simple.

If you want to go a little further, you should consider the content from the following brilliant presentation http://www.youtube.com/watch?v=H7PJ1oeEyGg

How to make your RDBMS data go faster

So, how do you make your RDBMS data go faster with minimal effort ? I'll cover some basic concepts that are often forgotten, ignored or misunderstood.

Fast Writes

If you want fast writes you need to concentrate more on the log file (in SQL at least) so that the transactions can be committed as fast as possible. If you are using a synchronous commit (mirroring, availability groups etc) then you want a network that doesn't lag. To get the log file quick you really need to concentrate on speeding up the IO. The log file is sequential so you want the transactions committed as quickly as possible. I wouldn't worry too much about the structure of the tables so much other than to ensure that you don't go silly with the foreign keys and indexes as they need updating as well. Things for you to be aware of here are page splits (as data gets inserted into the b-tree index) and locking of the data. By having the log file fast you reduce the duration that the lock is held for in effect. A lock is created, the change made and committed, this is the hardened in the log and the lock released.

TempDB

The single best option here is to avoid TempDB.

With SQL, if you end up using TempDB then this also needs to be fast. Again, use the SSD for this. It makes the world of difference. Traditional recommendations are to separate your logs and data files onto different volumes and an SSD is a great way of doing this cheaply (I would recommend putting the log files and TempDB together on the SSD unless you really need to crank out the performance). You should also add more files to TempDB with a general rule of 1 file per every 2 cores (up to 8 files) and that's likely good enough as a quick pass. If you want to know why then Google for 'SGAM contention'.

General Database Structure (under the hood)

I generally go further and split the database so that the biggest tables (or major entities if you will) have their own file group. I drop non clustered indexes into their own file group as well as well as create a new one the default file group. I do this so that the mdf file only contains the basic system information needed as this can speed up some recovery options.

Then each file group is given several files (for simplicity I generally recommend the same as you need to do with TempDB). Why ? Well, the more files you add the faster you go (to a point) and it helps with hyperthreading. SQL uses a proportional fill algorithm so ensure all of these files are created the same size too. I have been known to move individual file groups to different RAID sets depending on the characteristics on the type of data (R5 for reads, R10 for writes). I also prefer dedicated spindles as you get a lot more performance and don't wait for some other process to finish with the disks that you need. I can very happily recommend FusionIO and suggest dropping all files plus log and TempDB onto a drive (it's pretty mind blowing for performance).

Work with your SAN admin if you can and give them detailed info on what you need to achieve. Tell them why you need dedicated IO and what performance characteristics you need. If that doesn't work, try FusionIO and tell them you don't need them anymore :-)

Data Reads

For reads, as a general rule of thumb, if you want you data to go fast, you want to get the entire set of data plus indexes into memory. If you can't get the data into memory, then you need to get it from disk. It sounds simple, but how do you do that ?

If you look at the Microsoft Fast Track Architecture you will see they go to a load of pain separating things out to maximise the speed. Basically using a lot of disks (a RAID 5 set per core in essence). Smaller and cheaper set-ups don't need that although you must remember to get decent IO performance to suit. 

I honestly don't think that this is the right approach for most cases. It is perfectly valid and simply assumes you need to perform scans on the biggest set of data within the database. To me, this is throwing a lot of money at the problem.

Getting the data itself right is the better approach if you have the time.

To really get your data fast, you have to learn about b-tree indexes (balanced tree). Once you understand how to make use of these (I will blog about these too shortly) you can learn how to index your data so that your queries are optimised. The effort you need to put in is in the design of the table, but more importantly the indexes and them the queries that fit on top. If you use an ORM to save to development time you still need to understand what is being asked for and build the indexes to suit. Don't be lazy and assume that the ORM gives you the most performant queries. It won't. Check the queries and pick the battles you need to fight.

The key to this (in SQL) is the execution plan. This gives you everything you need but it takes some time to get to know this in detail. You need to aim for a single version of the execution plan so that you don't spend time compiling a new plan each time.

What you are aiming for is Clustered Index Seeks where possible. You need to avoid Table (or index) Scans.

Small data types are worthwhile the effort when you are dealing with high concurrency systems. It might seem like micro-optimisation but it isn't. Bringing back data that you already have is also something to be avoided. This is where you will have a potential disagreement with your developers as that approach will be better suited to the object they want but ultimately it hampers the speed of your data.

I'll write another blog soon on why joins aren't really a bad thing if you do them right.

As a quick summary

For fast writes, speed up your log file
For fast sorts and grouping, speed up TempDB.
For fast reads, get the data in memory or get the IO right if you can't.
Overall, get the data structure right, get the indexes right and tune them hand in hand with the queries.
Aim for a single execution plan (no compiling after the first hit) that gets re-used.
Keep your queries simple and avoid putting calculations in the where clause if you can (these will be re run for every line that matches).
Don't keep returning data you have just received.
Take the approach of a precision missile strike rather than carpet bombing the whole thing.





Friday, 10 May 2013

How to asynchronously re-build your indexes in SQL

Sometimes you want to do something asynchronously in SQL and it really wasn't designed for that.

The example shown here is to re-build indexes for all of your tables at the same time. By this, I mean that a different SPID is used for each table so that they all run at once.

Be warned, this has the potential to warm your server up somewhat. I'm lucky that when I needed to do this I had a very good server, SQL 2012 Enterprise (so I could use the ONLINE = ON option, and a FusionIO card meaning that IO performance was not a concern). I wouldn't recommend using this in a production scenario, but if you need to do this during a maintenance window and don't want to sit there waiting as you do one index at a time, then this might help.

We needed to move a lot of data to a new server and then re-build every index before we went live. The window was tight so the decision was made to use more of the servers potential. Below is the approach we used.

The basic idea is to fire off a new SQL Agent job for every statement and rattle through a list of tables to do this. The jobs are set to delete themselves once done. It's nice and simple once you have it figured out.

USE MyDatabase
GO
SET NOCOUNT ON
DECLARE @TableList TABLE (Id INT IDENTITY(1,1) PRIMARY KEY CLUSTERED, SchemaName VARCHAR(100), TableName VARCHAR(100))
DECLARE @SQLCommand VARCHAR(1000)
DECLARE @MaxId INT
DECLARE @Counter INT
DECLARE @MySchemaName VARCHAR(100)
DECLARE @MyTableName VARCHAR(100)
DECLARE @MyDB VARCHAR(100)
SET @MyDB = db_name()
------
INSERT INTO @TableList (SchemaName, TableName)
SELECT TABLE_SCHEMA, TABLE_NAME FROM INFORMATION_SCHEMA.Tables ORDER BY TABLE_SCHEMA, TABLE_NAME
SET @Counter = 1
SET @MaxId = (SELECT MAX(Id)+1 FROM @TableList)
------
WHILE @Counter < @MaxId
  BEGIN
    SELECT @MySchemaName = SchemaName, @MyTableName = TableName
    FROM @TableList WHERE Id = @Counter
    SET @SQLCommand = 'ALTER INDEX ALL ON ' + @MySchemaName + '.' + @MyTableName + ' REBUILD WITH (FILLFACTOR = 90, ONLINE=ON)'
    IF EXISTS(SELECT * FROM msdb.dbo.sysjobs where name = @SQLCommand)
       EXEC msdb.dbo.sp_delete_job @job_name=@SQLCommand;
    EXEC msdb.dbo.sp_add_job @job_name=@SQLCommand, @Delete_Level=3;
    EXEC msdb.dbo.sp_add_jobserver @job_name=@SQLCommand, @server_name = N'(local)';       
    EXEC msdb.dbo.sp_add_jobstep @job_name=@SQLCommand, @database_name = @MyDB, @command=@SQLCommand, @step_name=@SQLCommand, @on_success_action=3;   
    EXEC msdb.dbo.sp_add_jobstep @job_name=@SQLCommand, @command='SELECT 1', @step_name='End', @on_success_action=1;   
    EXEC msdb.dbo.sp_start_job @job_name=@SQLCommand;
    SET @Counter = @Counter + 1
  END
GO

Oh and watch for your transaction logs when you do this (if in Full Recovery Mode). They'll get big very quickly. Make sure you have plenty of space !

How to break a SQL database into manageable sections

As databases grow they can easily become too complex whereby the number of tables renders any attempts to document and understand them pretty much impossible.

Schema diagrams of an RDBMS are something incredibly useful to a data professional as that will show the design of the tables and the relationships between them. Generally drawing them is relatively painful so the best approach is to use Visio Professional and reverse engineer the database into a schema diagram. This takes a few seconds normally.

But what happens when the diagram you get contains several hundred tables which cover multiple domains all intermingled and seemingly no way of unravelling this into something legible ?

Well, this happens a lot, so here is my approach for making sense of the chaos. Be prepared for a lot of work, but hey this is a complex task so hopefully some pointers will make this easy. There is a fair bit of manual processing but hopefully someone can automate this and save more time.

Warning, this is NOT an easy task but it is do-able.

First up, forget Visio Pro for now. We will come back to that later.

My preferred method is to start with RedGate's Dependency Tracker 2. 
http://www.red-gate.com/products/sql-development/sql-dependency-tracker/ 

I would advise you get the full toolbelt if working with SQL as it will save you a lot of time.

Anyway, when you point this at your database you get a different approach to diagramming. Initially this won't look readable, but bear with me. Add all of the tables you want into the project and let it generate the diagram (this will be quick)




You can see several very large circles and it's those you are interested in. This is where the pattern in the chaos starts. The centre of each circle is a table that has a lot of relationships. Make a note of the tables in the centre of the biggest circles. You probably don't have much more than 20 or 30 of these. You will probably find that these are some of the major entities or domains that you would expect in your business (Customers, Orders etc...). Write this list down.

Now, start up a new project in RedGate Dependency Tracker and just pick a single table from your list. When you see that diagram you should ideally have a single circle showing. You now have everything that depends on a major entity (Customers for example).




The pain in the arse is getting that list into something useful. You can get an XML list of the dependencies which is a good place to start.

With a bit of work you can easily get this into a list of tables that directly need the major entity you are working with. This is all you need here. Don't worry about what else relates to everything else. We are trying to break this into a decent slice of the puzzle so we can figure the rest later.

Get yourself a list of all of the tables in the database 

SELECT
  TABLE_SCHEMA,
  TABLE_NAME
FROM
  INFORMATION_SCHEMA.TABLES WITH (NOLOCK)

  
Drop this into Excel and add a new column for the major entity that you are working with.

Rinse and repeat for each of the major entities so that you have these covered. You will find that the large majority only really relate to a single major entity, however, you will have some that don't. Make a quick assumption here so that each table has a single associated major entity. Don't worry about accuracy too much as this will become clearer later.

Now, back to Visio (and you need the Pro version for this feature). You can now reverse engineer the database into a diagram. Select all of the tables you associated with the major entity (yawn - boring bit).

When you draw your diagram out you then should be able to see something a lot easier to read. If it's only a handful of tables then you can make sense of it.




If you want to take this further, you can then overlay which major entities are relevant to this diagram. To do this, you need to pick the tables off one at a time and work through the foreign keys. Don't add in the other tables, but rather add in a single box that gives the major entity name (Orders for example). You can add the relationships to this 'block' without having to add the detail. You will need to follow the foreign keys for each table and see where they relate to. The script below will show you what foreign keys from a table relate to what.


USE MyDatabase
GO
DECLARE @MyTableName NVARCHAR(100)
SET @MyTableName = 'Customers'
SELECT
  C.TABLE_SCHEMA AS Owner_Schema,
  C.TABLE_NAME AS Owner_Table,
  KCU.COLUMN_NAME AS Owner_Column,
  C2.TABLE_SCHEMA AS Related_Schema,
  C2.TABLE_NAME AS Related_Table,
  KCU2.COLUMN_NAME AS Related_Column,
  C.CONSTRAINT_NAME AS FK_Name,
  C2.CONSTRAINT_NAME AS PK_Name
FROM
  INFORMATION_SCHEMA.TABLE_CONSTRAINTS C
  INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU
  ON C.CONSTRAINT_SCHEMA = KCU.CONSTRAINT_SCHEMA
     AND C.CONSTRAINT_NAME = KCU.CONSTRAINT_NAME
  INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC
  ON C.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA
     AND C.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
  INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C2
  ON RC.UNIQUE_CONSTRAINT_SCHEMA = C2.CONSTRAINT_SCHEMA
     AND RC.UNIQUE_CONSTRAINT_NAME = C2.CONSTRAINT_NAME
  INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU2
  ON C2.CONSTRAINT_SCHEMA = KCU2.CONSTRAINT_SCHEMA
     AND C2.CONSTRAINT_NAME = KCU2.CONSTRAINT_NAME
     AND KCU.ORDINAL_POSITION = KCU2.ORDINAL_POSITION
WHERE
  C.CONSTRAINT_TYPE = 'FOREIGN KEY'
  AND C.TABLE_NAME LIKE @MyTableName
ORDER BY
  C2.TABLE_NAME


Once you rinse and repeat for each major entity you will hopefully find you have a readable database schema for the relevant part of the database.

To be honest here, it's a hell of a lot of work, but if you really do need to do this (and I just have) then this approach is worthwhile exploring. Once you have an appreciation of the shape of the data you can then work out the characteristics and then figure out how to re-factor this part of the database etc...

Hope this helps


R

CV Driven Development

Over recent years I've watched a worrying new trend emerge which I think of as CV Driven Development. What I mean by this is that people...