Tuesday, 8 October 2013

Thoughts on NoSQL

I've been thinking about NoSQL solutions a lot recently. It comes with the territory I guess. 

If you imagine any radical change as a swing, we've probably come to the extreme at this stage and are swinging back the other way somewhat. That is back towards RDBMS's. I'd imagine that over time things will settle part way between the two with the sucessful vendors being the ones that offer the most features of both. NoSQL options are adding in SQL interfaces and discovering the problems that RDBMS's have gone on to address over the years (indeed they are likely to make similar mistakes).

Google have certainly found that NoSQL solutions and the ideas of Eventual Consistency have caused the sufficient problems to move back to an RDBMS (but retaining the nice features that NoSQL offer)

http://www.theregister.co.uk/2013/08/30/google_f1_deepdive/

Google also use RSBMS's heavily (having recently decided to move to MariaDB from MySQL).

I started to dig into the NoSQL thing a bit more and from what I can see it mostly seems to stem back to a white paper from Amazon about scaling data at extreme scale. If I can find the link again I'll update this blog post.

The basic premise of the paper highlighted something that Ted Codd also pointed out back in the 1970's as he worked on the foundations for relational databases. This was that there is an overhead in checking constraints on data in a relational system. So think of there being overhead for foreign keys and you get the idea. It is absolutely true in that there has to be some delay while that work is done (we are talking very small fractions of time though depending on scale). Amazon's paper found that at 'extreme scale' this caused a problem for them with the expectations they had for their systems. 

Part of the problem that Amazon was aiming to solve was that they needed systems that would guarantee writes for the 99th percentile of their customers. In most cases you would typically look at the 95th percentile, so 99th is a whole different argument as it brings in most of the edge cases and that can change the game. 

Do this at 'extreme scale' (with very high concurrency) and it becomes a very difficult problem to resolve.

Amazon also aimed to address the 'delays' that you get from an RDBMS which is in the locking, logging and latching of the data which most developers perceive isn't fast enough for their needs. The best approach I've seen to improve on this is from VoltDB (another Michael Stonebraker product). It's early days for this and while they only offer support in office hours EST it will stay off my radar. They are both absolutely right in that there is time lost here. However, how much time and what impact that has for you is an interesting question. If we are talking the last few microseconds then yes it is valid, but if that doesn't really matter to you do you need to worry ? If you have delays introduced by poor coding etc... then you likely aren't at the stage where you need to worry here.

The NoSQL options here stop you worrying as it's generally a fire and forget approach. This is fine until something goes wrong. To help make it better (with say MongoDB) you can turn on journalling, but then you have re-introduced a basic concept you were trying to avoid. Hmmm...

Amazon were quite right in that the delays from a relational system would likley impact their expectations so they created their own approach which is where the NoSQL approaches stem from. It might be possible to argue that you could overcome a lot of the problems that both Amazon and Codd identified, but I'm sure they have all thought it through so lets give them credit and assume they were right.

We now move onto the 'joins are bad' argument. Feel free to read my other post on this, but as a basic statement I'd say that people misunderstanding how to work with data is the problem and that joins are perfectly fine for the vast majority. Those arguing against them are likely developers and I'd suggest they probably don't know RDBMS's enough to have a qualified discussion.

A lot of latency in databases comes from storage whichever option you choose. Storage desperately needed to move on and has done so now with NAND flash (even though it is a 25 year old idea). Moores law doesn't apply to spinning rust so it's hampered data as we've exploded the use of it.

What we need to remember is that Amazon was aiming to solve Amazon's problems. Not yours. They have offered DynamoDB to the public for a while but that's sensible to make revenue from it once they had implemented it for themselves first.

A number of other approaches have come along the way and offer solutions that allow you to move away from RDBMS's. Do you really need to solve the problems that Amazon needed to ?

Most of the NoSQL options appear to try to solve the problems that they understand from Amazon's findings. Most businesses don't need to scale to the extremes that Amazon is at. Graph databases might not be new, but Neo4J looks very interesting and I see good potential there in the right places. MongoDB is based on ideas from Lotus Notes which was awful IMHO (I spent 6 months as a Lotus Notes developer back in the day).

In terms of which platform to choose ? Well, it's an entirely different question if you are a start up or have an established platform. The true TCO can be way higher than expected if you swapped it all in (especially if you are looking at this for an Enterprise scale business). The costs look good for single servers, but try and see how much it costs for trying to put 1TB into RAM in a sharded setup. It ain't as cheap as you might think, especially when you consider support and redundancy or failover, dev, test, qa and so on. You can achieve this with lower costs if you trade off RAM for fast enough storage (say FusionIO) but you loose the scale out argument. Each approach is a balance of trade offs. Yes MS charge a lot and Oracle more. It's a stick I get beaten with most weeks and I wish it was better.

Developers often think that saving costs and time for development is the only consideration. It is very important yes, but if I save a few grand on Dev time but spend £3m in production then it's not an easy sell to me. It's simply because of different needs of the data that stops each side seeing the other's argument. (For the record, I've been a Dev for many years, then SDM, then DBA, then Data Architect and now Enterprise Data Architect who also owns a small software business).

The Agile movement has been incredibly worthwhile and beneficial but we might have gone a bit too far. In the lean world you only think about the next problem for development. However, from an enterprise architecture point of view I'm interested in making sure that when you come to the bigger problems we haven't taken the wrong direction earlier on. I'd love to hear a developer or SDM show me where the maths makes sense for the business whereby the changes we make are going to bring in a higher return and cover it's basic costs. It's the most basic concept of business and yet is often forgotten in the rush to develop the next feature. It'll get you somewhere down the road if you are lucky (and half decent) but at some point you have to turn that into profit.

Start with the basic maths. How big is the data. What will it take to run it. How fast do you need it. Can you afford to change it and if so which gives you the best return ? Don't just start coding. Measure twice, cut once my Dad always used to say.

So...right tool for the job yes (polyglot persistence), but a bit of common sense and some basic maths would go a long way on both sides. Having a platform that does 90% and then using something else for the edge cases is far more sensible. Remember that NoSQL stands for 'Not Only SQL' instead of 'Anything But SQL'. 

Wednesday, 3 July 2013

How do you justify an 'in-memory' datastore solution for everything ?

I've been doing some thinking on this over the years and again more recently.

Forget any arguments on the shape of the data you want to see (in and out). Forget which particular product is the preference and the maturity etc of that product.

It's some basic maths that sticks in my mind somewhat if you do everything as an 'in-memory' solution.

So....lets start with the basic maths.

I currently have a 1TB footprint of my data. I know I'm going to grow and if I give up a relational approach I'm likely to need some more space. Lets call it 2TB for the sake of argument. Hardly a massive data footprint as VLDB's are currently defined as starting at 1TB and data is growing a lot these days.

So, 2TB. In memory. That's a lot of memory.

I'm going to need 18 servers (with 60GB of RAM) per Terabyte. You can go for more memory if you like but you aren't helping your 'scale out not up argument'. It's an arbitrary number I suppose. I'll also suggest say £3k per server is likely.

I've solved having a solution like A-L and L-R and R-Z with my data split across nodes but I now have 18 single points of failure with data sharded across it. 

Hmmm....Best split the data so that it never resides on just one node (so lets say 2 nodes is acceptable). That means that I need twice the memory footprint I was originally thinking of.

I'm now looking at 18 servers per TB which gives me 36 servers and now I need x2 of that to give me redundancy. 72 servers so far. Keep with me.

OK, I'm going to throw some more things into the mix. Yep, a second data centre for DR. Bugger. Erm....hang on a minute. 144 servers now.

I might be able to split the estate over two data centres so I need to have a think about the best balance for the business there. For now, let's stick with the 144 servers (yes it helps my argument, but it is my argument so ner).

Right...we have everything we need now don't we ?

Erm....No


  • Dev
  • Test
  • QA
  • Sandbox


Ah.....

Right, so I can bin some of the redundancy and keep them simple.

Lets say 144 servers for Live, 36 for Dev, Test, QA and Sandbox each = 288 servers.

288 x £3,000 = £864,000

Awesome. We now have everything we need !

No

Did you think about support ? Come on, you are looking at putting this live and you really should think about it. If you are talking MongoDB you are probably looking at £5k per server - call it £3k if you can negotiate a good deal.

That's another 144 x £3,000 which = £432,000

Ah

So we need 288 servers and have spent £1,296,000

And NOW we now have everything we need !

No !

Seriously ?

Have you thought about monitoring ? BI ? Reporting ? and so on ?

Righty ho. Bet you didn't think about power, cooling and rack space did you ?

Or switches to make the 288 servers talk to each other.

Or cables ? (OK, I'm being somewhat pedantic).

Lets say you use 300 watts per server. That is 300 x 288 = 86,400 watts ! (360 Amps) 

I'm having a Doc Brown moment here if you can't tell.




At 42u per rack I'm going to need about 8 racks with some wriggle room. Assuming I can cool a rack full of pizza boxes with no gaps. Did you calculate the BTU's per hour that you need to cool ? No, I bet you didn't.

In case you haven't been to a data centre, that's a lot of floor space for 2TB.

What happens when you grow bigger than anticipated ?

Maybe, just maybe, you should pick your battles and work out what does need to be in memory (and realise that some solutions you already use are already using data in memory) and if you do genuinely need a very specific solution then go for it with the bits that will need it as opposed to everything at once.

For smaller data stores it does make sense, but there is a tipping point where you start to feel uncomfortable.

Maybe they only really make sense if they are cloud based and the hardware becomes someone else's problem. It does add other things to think about but I've leave it there for now.


Microservers or Blade Servers might be worth considering in order to reduce the physical footprint and possible cost (although you still have a lot to pay for)

Friday, 28 June 2013

MongoDB vs SQL Insert Comparison

2 years ago I read a blog post that stated MongoDB was significantly faster for writes than SQL.

The original post seems to have disappeared although there was a response here 

http://blogs.lessthandot.com/index.php/DataMgmt/DBProgramming/mongodb-vs-sql-server-insert-comparison

I decided at the time not only to take up the challenge, but to get the guys on my DB team to have a go as well.

The basic idea was to create 500,000 Unique Identifiers and insert them into a document or into a table.

The MongoDB option in the original post said SQL would take 1.5 minutes and MongoDB 30 seconds. You have to create these too, not grab them from somewhere else.

As it turned out the above post suggested it could be done in 6 seconds. I thought even that could be improved on.

The entire DB team (about 8 of us) all comfortably beat the 30 second watermark and most got down really low. I'm not bragging, but I won and my solution takes approx 3 seconds on my 3 year old work PC (after the query plan has been cached).

CREATE TABLE dbo.MongoCompare (
  GUID UNIQUEIDENTIFIER DEFAULT NEWSEQUENTIALID() PRIMARY KEY,
  VALUE INT)
GO


SET NOCOUNT ON
BEGIN TRAN
DECLARE @Id INT = 1
WHILE (@Id < 500001) 
  BEGIN
    INSERT  INTO dbo.MongoCompare WITH (TABLOCK) (VALUE)
    VALUES (@Id)
    SET @Id = @Id + 1
  END
COMMIT

IF (SELECT @@TRANCOUNT) > 0 
  ROLLBACK TRANSACTION



Whether or not you prefer MongoDB or SQL is sort of irrelevant for this. It's just something to mull over. You need to do any comparisons with equal skill sets to ensure you have the best answer for what you are doing.

The trick to my answer was to use a transaction and commit in one fell swoop at the end. Something to bear in mind is that the original post stated that for the duration MongoDB sent the processor crazy. For my option it barely tickles it (a couple of percent on one core)

Thursday, 27 June 2013

Let me worry about the data

Seriously. It's what I'm here for. I'm the one who worries about the detail.

I quite often wonder why being a data professional is so hard and find it's often that you end up having too many conversations about what to do with the data.

Yes, I know all about the impedance mismatch between object oriented systems and relational databases. For the record I've actually spent more time as a developer than dedicated to data. I was a Delphi developer for years and wrote software for most of the motor manufacturers (financial and marketing systems).

I went down the dedicated data route for a few reasons. Money was one reason as my eldest child was on the way so I knew I needed to bring more in (I have to be honest) and alongside that I've always had a passion for data and find it far more of a challenge tuning databases (give me the scary ones please). I did all of the courses on SSADM (Structured Systems Analysis and Design Methodology) so you know I've been around a while. I've worked with Access, Paradox, Interbase, SQL, MySQL, Lotus Notes and plenty of others along the way.

There are some paradoxes that annoy me a bit. Developers tend to think about the database as a black box yet try to get involved and assume that they can really get the best from a database. Of course, 'anyone can write a select statement' and herein lies part of the problem. Databases don't tell you in an obvious way that you haven't asked for what you need in the best way. It's a system that gives you the best compromise based on cost of execution as it knows that not everything that comes through is quality. If you get the data, that's cool but then we get hit with the 'databases are the bottleneck' argument especially as load is added. For me, this is where a lot of the fun is.

Imagine the database were a bank for a minute. You are interested in putting money in and getting money out (at it's most simplistic). Beyond meeting the cashier you don't have any involvement in what happens to the money. You don't need to care when the money is put in the vault. You don't have any involvement in the staff rota to man the cashiers desk and so on.

What matters to you is that you can put money in (in coins, notes or cheques) and that you can withdraw your money in various forms too. It's a standard interface as such. Sometimes you might want to do something different like a bank transfer so provided the bank knows about it they can handle it. 

If you wanted to wrap your 5 pound note around a rock and throw it through the window then next time you wanted to staple it to a tap dancing gibbon and shove it under the door then fine (ish) so long as we know what's coming and how (amusingly, I think I've just created a brilliant analogy for nHibernate generated queries).

So for the database, don't lecture me on how we need to work with the data. I'm here to help and sometimes even happy to do so :-) I'll also sort out backups, indexes, high availability and so on without bothering you.

Just tell me what shape the data is coming in and how you need it back plus how fast you want to go (I bet we can send you data faster than you can consume it). If I genuinely think we need another data technology I promise I will speak up and let you know.

As I said, don't worry about the data. It's my job to design systems that keep it available, performing well, accessible and recoverable. If I make a mess, it's my head on the block. 

Work with me and let me help compliment your code. 

The best systems are made when people collaborate. We need UX guys working with the developers, developers working with the DBA's and DBA's working with the infrastructure team to get the best from the whole stack. One person can't do it all so use the strengths of the people around you. We just need a little bit of faith. We won't let you down.

Wednesday, 26 June 2013

A quick glance at architecture - SPOLDATGOS

I had some sound advice from another Enterprise Architect the other day on what you need to consider when Architecting systems.

I thought I'd make myself a quick note here which may also be of use to other people.

SPOLDATGOS is what he said to me.

Services
Processes
Organisation
Location
Data
Applications
Technology
Governance
Operations
Security

These are the main areas you need to cover. It shows you have considered what are you going to do, how are you going to do it, who is going to do it, where are they going to do it, how will you know it is done, what are you going to do it with, what technologies will you use to do it, how do you control what you do, how do you manage this when it is live and how do you secure it.

Sounds simple, but these are the things you need to answer.

Monday, 24 June 2013

Monitor it, look at it, understand it and then do something

I've worked on a lot of systems since I left university in 1996. I've designed them, built them, supported them, re-worked them, tuned the hell out of them and indeed have broken some along the way.

With large scale high concurrency systems that have zero downtime you have to get your skills up. If you make a mistake you can quite often lose your employer a serious amount of money. For example, if you have 20,000 concurrent people on the website (not that big a number for a dotcom) you are going to find out very quickly if something isn't right. If you aren't informed then it's a problem.

The problem that we face is that a lot of companies look at their concurrency issues and immediately assume that they need Facebook or Twitter levels of solutions and therefore overcomplicate things. 

Solve the problems you actually have and not the ones that you don't.

The trick to doing this is to keep things simple, monitor it, actually look at it and understand your monitoring and then (and this is the crazy bit) do something about it. You have to understand what you are asking of your systems. Obsess over the details if needs be but as a minimum communicate what you see and be passionate about it. People who don't understand you will often buy into the passion as they likely trust you know the technical detail. Ideally you should fail fast and fix fast. Don't tie yourself in knots adding more and more in. This is where Agile development helps a lot as you deal with smaller changes and can find problems easier.

A lot of companies will buy in monitoring systems and then put people in front of them who can follow process but don't actually understand what happened, why and what needs to be done to stop it happening again. They don't see what will happen when the problem happens again and then don't understand when it isn't worth fixing either.

I appreciate it's good to have the latest monitoring system for your CV, but you have to be able to understand it and react accordingly to benefit the business that employs you. You need a supportive structure to allow you to flag things. You need a business that will actively deal with technical debt as well as constantly pushing new features. You have to do both. If you don't you will cease being able to innovate and as your business adds more users (more high concurrency) you will stall at some point and likely lose your good staff.

From a development perspective, dealing with high concurrency changes the game somewhat and if I'm honest, a lot of developers just don't get it (the best ones do). In terms of developing a brilliant bit of software that has suitable tests wrapped around it for functionality, yeah, you can get a lot of developers without too much of a problem. TDD (Test Driven Development) doesn't often include testing things with a lot of users doing stuff at the same time. Tests should include load testing as a minimum with realistic load. Don't just fake out things from part of the stack, run the tests properly and re-create the problems you had in live recently. Then monitor, understand and solve them.

To do this properly you need the time to properly flush things out and get a routine going. Once done, it shouldn't be difficult to build in so that you have this automated. You need supportive people around you who let you address these things. If you don't, you end up being part of a system that is built to handle all of the compromises and not what was originally intended for the business or what the business expects it to do.

Take this to the extremes and the business will then bring in some highly paid people who think the problem is bigger than it is (as they have no idea of the detail that actually needs fixing) and then will try to apply bigger solutions as they think it is what is needed. As time progresses you find you have some more systems that don't really add anything and the underlying problems haven't gone away.

Treat every error as lost revenue. Go and count up all of your errors and put a nominal value against them. Scary isn't it ? When errors happen, think about that as lost opportunity and revenue. Always keep your live estate at the forefront as that's where the money comes from.

Monitor it - if you don't then how the hell do you know what's going on ?

Look at it - Seriously, go and have a look. This is where a lot of companies fail. See what happens when user connections go up, see what happens when IO maxes out or a component system becomes unavailable.

Understand it - Sounds easy. It isn't. What are the implications of a metric changing ? What else changes and why ? Don't just look at CPU, look at IO, look at processor queue lengths, look at memory use and indeed not just the quantity in memory, but the churn moving data in and out of memory. Look at the network packets and see if the data flowing out corresponds with the CPU and IO peaks. Delve in deep and see what's actually being done. Look at when metrics go down as well. If this isn't what you expected, is something wrong ? Is it right and we can do more of the same ?

Do something - What is the point of doing any of this is you can't effect some change to improve it ? Go and find the person who can change it and convince them. If that doesn't work, go up the ladder until you find the right person. If you keep running into obstacles, collate the issues together, don't give up yet. There is a tipping point whereby you walk away but often this can be avoided.

Thursday, 13 June 2013

Don't try to make an inappropriate design work

If you look at the construction of the Leaning Tower of Pisa you can see some parallels with what you can find when looking at how some software systems are built :

•1173 AD - First floor completed

•1178 AD - Second floor construction - Tower starts to sink due to weak unstable subsoil/clay (This should have been the warning point)

•1272 AD - 3rd, 4th, 5th and 6th floors constructed  with one side taller than the other to compensate (the tower is now curved)

•1319 AD - Seventh floor completed

•1372 AD - Bell chamber added

•1838 AD - Decision made to dig out a walkway so visitors could see the carefully crafted base (this made the lean worse). Mussolini intervened to try and straighten the tower. He ordered the foundation to be filled with concrete. This sunk into the clay and the tower leaned further.

•1934 AD - An engineer drilled 360 holes into the base and filled them with mortar. The tower leaned over further.

•1993 AD - 650 tons of lead were hung from the North side to stop the lean and it worked for a while.

•1995 AD - Decision made to try and increase the foundations on the South side. They froze the ground with liquid nitrogen to stop it moving and started to remove stones that could be replaced with metal rods. The stones were part of the original foundation of the building (this is the nearest the tower has come to disaster). To counter this quicker lean they quickly added 250 tonnes of lead and decided on a re-think.

•1999 AD - British engineer came up with a plan to remove ground from under the high side (instead of adding under the low side).

•2001 AD - Work on latest plan complete and tower back straight by 16 inches (to 1838 levels of lean)

There was another similar tower built nearby in Pavia which fell over in 1989.
There are some concerns now about the masonry that has suffered from an increased load over the years and the worry is that this may eventually crumble.

Trying to make an inappropriate design work :

So many system designs are so much like the Leaning Tower of Pisa. People charge ahead with a rushed design and objects get put on top. Because the design doesn't work right they have to use lots of code to correct the design, and then more code, then some code to fix the problems.

Unlike compiled executables, database designs are hardly ever corrected and re-worked. If a program doesn't compile the code is corrected until it does.

A good system design works with the code and also eliminates the need for thousands of lines of code.

The problem with RDBMS's and Mechanical Storage

For the last few years I've had a number of discussions surrounding 'in-memory' databases and this has typically been on the basis that if you get the data into memory then it's as quick as you can go (it misses out on how you work with the data btw).

For the most part, this is accurate (from a high level viewpoint), however, there are some aspects of this that are misunderstood or (dare I say it) not thought through properly. The faster you get your data to the processor the faster you go. Very few people seem to tune much at this level but if you are interested please watch http://sqlbits.com/Sessions/Event9/Finding_the_Limits which is by Thomas Kejser and is truly eye opening.

The presentation makes a massive leap forward (not only with Thomas's approach, knowledge and skills) but also by using FusionIO for the storage.

What happens if you don't have FusionIO and have to rely on traditional mechanical storage ?

This is one of the main problems with relational databases. The approach we take with relational databases and normalising our data goes way back to 1970 for First Normal Form (1NF),  Second (2NF) and Third (3NF) followed in 1971 then Boyce-Codd Normal Form (BCNF) in 1974. Back in those days we didn't have much data and the speed that we could work with it was pretty slow. I suspect that one of the main reasons behind normalisation was really to reduce the footprint and the working set of data as the costs of storage were prohibitive.

Since then, hardware has become faster and data has grown in size. Unfortunately we hit a tipping point a while back that I think was somewhat masked. Moore's law gave us faster processing but it didn't do much for the storage. We had SATA and the disks there typically spin at 7,000rpm. SAS came along and the spin speed went up to 15,000rpm. Our data growth was such that what we wanted to do worked and fit onto this storage and we got away with it. SAS drives haven't really changed in the last 10 years or so. Why ? Well, it's to do with physics and the speed that we can get the disks to spin. There isn't really much that can be done to improve on this (probably too complex to delve into here). We can add more platters to get more data on, but that doesn't make it faster. We can short stroke (use the outside of the disks) but that doesn't really help when the disks are full.

The physical head that reads the platter still has to move across the platter to retrieve the data and the more work it does, the more latency that will eventually show through. We can add more spindles and divide the load up so that we hopefully reduce the latency and spread our bets if you like.

So, next up is to move different RAID sets to try and reduce the random IO that you will eventually get. 

Following that, dedicated spindles so that you don't wait on someone doing a powerpoint presentation while you try to take a booking on your website. If you follow the Microsoft Fast Track Architecture it basically gives a RAID 5 set of disks to individual cores on the assumption that you have no indexes and table scans will be done everywhere.

If you look at Column Stores they are designed to minimise the disk seek time by addressing how the data is physically stored on the disk so each physical movement is much more effective.

Add to this caching (in memory) so that you hit the storage less.

All the while, our other hardware is getting faster, our data is getting bigger and our expectation on faster systems is getting less tolerant of delays. Most people haven't figured that synchronising the cores on a CPU is getting more complex so there is likely a tail off in performance (again, see Thomas's presentation)

So then we have the 'NOSQL' options. This then trades off certain aspects for speed with some solutions, or moves away from an enforced structure and moves that to the individual document on the assumption that joins are bad and so on (see my other post btw). 

'NewSQL' such as VoltDB goes off to address the underlying mechanisms (logging, latching, locking and b-trees) to crank more performance out there.

For 'in-memory' solutions we've stepped away from spinning rust, but what happens when the data set doesn't fit into memory ? Pick your preferred option here if you like but they all essentially work the same at a broad level. We can scale out, but then we need a lot of commodity servers which initially seem cheap, but still need power, cooling and rack space etc...

So now when we throw NAND flash into the mix (my personal preference being FusionIO) then we completely negate the physical limitations of the mechanical storage. We lose the latency and gain speed. So now the argument can be swung back around as the real problems with relational databases is the storage not being able to keep up with the quantity and required performance. Joins aren't then bad unless you do something stupid. Take away the physical limitations and do some sensible work and you can make it fly.

We can get the same gains with NOSQL and NEWSQL because we've binned the fundamental problem. You then have freedom and choice to find the right tool for the job.

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...