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.

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