ServiceStack – 2016
Introduction to ServiceStack
ServiceStack is an Opensource .NET and Mono Web Services framework built and maintained primarily by Demis Bellot. The ServiceStack project began in 2007 and has matured into a very popular framework now in 2016. This Code Review aims to take a close look at ServiceStack to see where it fits in the marketplace and provide enough information for developers to make an informed decision as to whether it is a viable framework for them.
What is ServiceStack?
ServiceStack is a framework trying to accomplish what almost every other Web Service framework tries to accomplish. It provides an alternative to popular Microsoft technologies like WCF, MVC and WebAPI for building scalable web services.
The ServiceStack framework pursues simplicity and is built around a simple and elegant core – with most of its features naturally binding to your models, not controllers (unlike all of Microsoft’s Web Services frameworks). This has many natural advantages in terms of its ease of development and maintenance.
ServiceStack’s core mission is to fight complexity, aiming to keep an invisible and non-intrusive API. Its thin and lightweight wrappers are used to provide a consistent and unified API around the core run-time IHttpRequest and IHttpResponse types. It lets you implement your service in pure, untainted C# accepting any user-defined Request and lets you return any Response DTO without any regard to endpoints and formats.
The key distinction that ServiceStack has in the market is it’s architecture. It has been designed to be message-based and comes with many advantages as the result. Message APIs are naturally batch-able and promote the development of coarse-grained service interfaces. This encourages fewer, more re-usable services that are better positioned for extensibility. It is a key benefit, since well-defined, non RPC/client-specific back-end services tent to outlive the UI’s and clients that consume them. ServiceStack has been built with the underlying belief that message-based design is the most optimal design for any remote service. The fundamental inspiration for building the framework was the belief that Microsoft’s frameworks have never gotten their architectures right.
ServiceStack, has a clearly defined goal and a dogma laid down about how services should be built. Because of this, ServiceStack is so much more targeted than the majority of its competitors which results in its simplicity. If the developer agrees with the rules imposed by ServiceStack and prefers to work with this kind of standardised framework, ServiceStack can, in turn, offer an increased simplicity and productivity. In effect, ServiceStack is trading the flexibility offered by some of the Microsoft frameworks for a more dogmatic approach, but a much reduced complexity. These dogmatic beliefs are an attempt at purity of design, but also offer a great deal of pragmatism.
Just one of ServiceStack’s beliefs is that there is a fundamental flaw in the way in which all Microsoft’s Web Service frameworks use mapping to C# methods. Over the years Microsoft has churned out: .asmx, CSF, WCF, WCF/REST, WSE, WCF DataServices, RIA, MVC and now WebAPI each with the same design in this regard. ServiceStack believes is a bad idea because it promotes chatty and brittle remote interfaces that don’t facilitate the easy creation of SOA-like APIs. ServiceStack’s key distinction in this area is that it is against the mapping to method signatures because they encourage developers to treat web services as “Just another method call”. When you evolve and refactor a C# method you have the opportunity to refactor all the call sites to meet the new method signature – whereas in a disconnect (and already deployed) client/server solution you don’t, you need to support both old and new clients requests and the only way to do that cleanly whilst still maintaining the same code-path is to pass messages between them.
Cross Platform Support
Because ServiceStack relies on the IHTTP interface rather than IIS it can run on both .Net and Mono. With ServiceStack you can take advantage of the flexibility in choosing your own hosting system which can result in cheaper pricing on Linux because of the licencing cost. ServiceStack allows you the option to chose your own hosting system. Being available on Mono allows it to be brought to platforms like:
ServiceStack’s flexibility has been key in the promotion of the framework within tools such as Xamarin. This in turn has opened the framework up to a whole new audience of developers and users and is widely adopted and supported, even on the Xamarin Docs.
The beauty of ServiceStack
The beauty of ServiceStack is built on a highly flexible and simple core. ServiceStack doesn’t believe in building strong-typed APIs over everything, as it’s impossible to predict what new HTTP Headers/StatusCodes will exist in the future. So whilst ServiceStack provides convenient behaviour to accomplish common tasks, it also provides a flexible API that lets you configure any desired HTTP Output.
The ServiceStack framework will often seem to “disappear” because it’s so transparent (Server Architecture). This is because the framework contains everything that you fundamentally need to build a web service – IoC container, Serializers and so on. Although these services are contained within the Stack, ServiceStack does not require that you use them. There are many plugins that are freely available and installable with just a few lines of code, but ServiceStack includes the Services that work best in the framework and offers the highest performance and therefore are encouraged.
Behind the scenes, ServiceStack is built on top of Raw ASP.Net IHttpHandler’s. Existing abstractions and xmlconfig-encoumbered ASP.NET providers have been abandoned in favour of fresh, simple clean Caching, Session and Authentication providers all based on clean POCOs, supporting multiple back-ends and all working seamlessly with each other.
ServiceStack’s architecture is purposefully kept simple and introduces no new concepts or constructs and can all be captured in the diagram below:
ServiceStack’s Message-based design allows the easy support of typed, generic and re-usable Service Clients for all popular formats:
Having all clients share the same interface allows them to be hot-swappable at run-time without code changes. It also keeps them highly testable where the same unit test can also serve as an XML, JSON, JSV, SOAP integration test.
By promoting clean (endpoint-ignorant and dependency-free) Service and DTO classes, your web services are instantly re-usable and can be hosted in non-http contexts as well.
What ServiceStack aims to do is provide the developer with the full stack of services that would be required to build an API/web application.
The main components of the stack. Go on to say the benefits of having this stack laid out for you so you don’t have to worry about it. A good benefit of having these services built into ServiceStack is it eliminates the need for external dependencies.
There are more services than this but I wont go into them all in detail, just the default ones that make the most significance.
ServiceStack.Text is an independent, dependency-free serialization library that contains ServiceStack’s text processing functionality, including:
- TypeSerializer (JSV-Format)
- T.Dump extension method
- StringExtensions – Xml/Json/Csv/Url encoding, BaseConvert, Rot13, Hex escape, etc.
- Stream, Reflection, List, DateTime, etc extensions and utils
IoC (Inversion of Control) Container
ServiceStack uses a slightly modified version of Funq – which was adopted because of its excellent performance and memory characteristics. ServiceStack’s version of Funq has been enhanced with Expression-based Auto-wiring and lifetime Request Scope.
ORM (Object Relational Mapper)
ServiceStack.OrmLite is a convention-based, configuration-free lightweight ORM that uses standard POCO classes and Data Annotation attributes to infer its table schema.
OrmLite was designed with a focus on the core objectives:
- Map a POCO class 1:1 to an RDBMS table, cleanly by conventions, without any attributes required.
- Create/Drop DB Table schemas using nothing but POCO class definitions
- Simplicity – Typed, wrist friendly API for common data access patterns
- High performance – With spport of indexes, text blobs, etc
- Expressive power and flexibility – with access to IDbCommand and raw SQL
- Cross platform – supports multiple DBs running on both .Net and Mono.
ServiceStack has a number of different caching options available that each share the same common client interface (ICacheClient) for the following cache providers:
- Redis – A very fast key-value store taht has non-volatile persistent storage and support for rish data structures such as lists and sets.
- OrmLiteCacheClient – Supports all OrmLite’s RDBMS providers for using ane xisting RDBMS as a distributed cache.
- Memcached – The tried and tested most widely used cache provider
- In Memory Cache – Useful for single host web services and enabling unit tests to run without needing access to a cache server
- Aws DynamoDb Cache Client – For using with Amazon’s Dynamo DB backend hosted on Amazon Web Services
- Azure Cache Client – For using the Azure DataCache client when your application is hosted on Azure.
Validation and Error Handling
ServiceStack offers the Fluent Validation library by @JeremySkinner which is a very clean and DSL-like way to validate request DTOs. ServiceStack’s Fluent Validation feature is encapsulated in the ValidationFeature plugin which can be registered in a web service with just a line of code. The validation feature is very useful for validating request DTOs.
ServiceStack offers an array of error handling options that work intuitively out-of-the-box. ServiceStack allows the developer to idomatically throw C# exceptions directly in Services and trivially consume them on the client with minimal effort, intuitively and conventionally – allowing the opportunity to inject generic error handling routines to handle errors.
The error handling support works end-to-end where all errors get auto serialized into your response DTO and re-hydrated into a C# Exception on ServiceStack’s generic Service Clients. This allows you to idiomatically treat errors like normal C# Exceptions – providing easy access to rich, structured error messages in your clients.
Easy integration of Plugins
ServiceStack provides a very easy way of including extra functionality within your application. Plugins available include (but are not limited to):
- Auto Query (Querying support on RDBMS tables)
- Server Events (Enables server push notifications)
- Postman (HTTP request composer)
- Swagger (Documentation and HTTP request composer)
- RazorFormat (Support for the MVC Razor view engine)
- Validation (Fluent Validators)
- Authentication (Authentication and Authorization support)
- Session Support (Creates temporary ss-id/ permanent ss-pid)
- Registration (New user services)
- MessagePack format (Binary serialization format)
- ProtoBuf format (Binary serialization format)
- Request Logger (Request/Response logging)
- Encrypted Messaging (Enables Secure Channel for all Services)
- Cancellation Requests (enables cancellation of long-running services)
- Web Sudo (Enables extra layer of protection in UI for things like transaction confirmation)
The registration of some of the above plugins not only provide extra functionality, but do so at little cost of development time. The Authentication plugin, for example, provides full Auth support for OAuth 2.0 with just a couple of lines of code for registering the plugin, and some set-up to connect with your Auth repository.
ServiceStack puts a lot of emphasis on performance. This section of the review will take a look at some benchmarks.
ServiceStack already has a lot of benchmarks available on the main Wiki page, but a lot of them are out of date and some of them have been built using some dodgy code.
To make sure that the benchmarks measured are accurate and fair, I have built my own Benchmarks Repository that I use to measure the difference between different frameworks/libraries. The repository is available here:
To measure the end-to-end performance fully it is necessary to compare the results with other frameworks. For this test we will compare ServiceStack with WebApi and Nancy. The default Client for each of the frameworks are different so this test will first run with the frameworks default Client (to respect the wishes of the framework) and then the tests will be run with the same Client. For the same client measurements the RestSharp client will be used which should help to level the playing field and gather a consistent end-to-end measurement.
ServiceStack claims to be 3 times faster than Microsoft’s WebAPI according to the official ServiceStack wiki performance page here:
Here are the results of my own benchmarks:
|Framework||Client||Number of Requests||Time (ms)|
|ServiceStack||JsonServiceClient (Recommended)||10000||5973 ms|
|WebAPI||HttpClient (Recommended)||10000||8099 ms|
|NancyFx||HttpClient (Recommended)||10000||7988 ms|
The final results show that while ServiceStack is not 3 times as fast as WebAPI, it still outperforms it by about 30%. Not only that, ServiceStack also outperforms NancyFx which is actually very impressive.
ServiceStack.Text claims to be the fastest C# implementation of JSON serialization to date according to its official Wiki page here:
And the results of my own benchmarks:
|Serializer||Average Serialization Time||Average Deserialization Time|
The final results show that ServiceStack.Text does not outperform Json.Net for either serialization or deserialization in 2016. However, it is important to keep in mind that the results on the ServiceStack Wiki were probably correct at the time of posting, but since then there have been updates to Json.Net and as of 2016, it appears to outperform ServiceStack.Text for simple Serialization & Deserialization.
ServiceStack’s Modified Funq IOC Benchmark
Although not the most important benchmark for most people in terms of measuring API performance, I thought it would be a good idea to test out ServiceStack’s modified Funq IoC – for interest more than anything else. I found a very up-to-date and very comprehensive IoC benchmarks solutions provided by Daniel Palme and added ServiceStacks Funq to it. My forked repository for it is here:
The below is a short snippet of the results I’ve gotten from the performance test. It shows the ServiceStack’s modified IoC is slightly faster than that of the original Funq, even with the extra functionality that ServiceStack offers like the expression based auto-wiring.
As I mentioned above, this isn’t the most important statistic to do with ServiceStack as a framework, but it’s nice to know the little things about the framework. It is also worth saying that ServiceStack has plugins for other containers like Autofac and so on, so you are not stuck with Funq if you don’t like it. Again, props go to Daniel Palme for his excellent benchmarking solution. For Daniel’s in depth results for over 32 different IoC containers, you can find it here:
Documentation of any framework is a must-have for the simple reason that if a feature isn’t documented it isn’t likely to be used. Documentation can often make or break a frameworks popularity with developers. Luckily, with ServiceStack the documentation is vast and in-depth.
The main bulk of the ServiceStack documentation is contained within the ServiceStack Wiki, which is conveniently located on the official GitHub repository.
The Wiki has over 130 pages of information written at the time of writing and documents everything from the philosophy of what ServiceStack is all about, to the architecture, to advanced configuration options, to things like multi-tenancy. It is a very impressive collection documentation in terms of its detail, structure, and clarity.
For when the ServiceStack Wiki isn’t giving you the information you need, the next place to look is StackOverflow. The lead developer of ServiceStack, Demis Bellot, is very available for support on StackOverflow even for developers on the free tier. Often times, the answers from StackOverflow are written with the intention of being moved to the ServiceStack Wiki and go into a lot of detail.
ServiceStack also offers its Forums for a place to get answers to questions. To be a member of the forums and ask questions you are required to pay for ServiceStack (more information on Pricing section). It is the main form of support to paying members members alongside the ServiceStack Issues database where members can log bugs and expect to get them fixed.
ServiceStack has been a commercial product since the end of 2013 and has a single full-time worker available for support and development at all times. The packages available are:
- Starter – Free
- Indie – $299 per developer
- Business – $999 per developer
Judging by the reaction from the public, the vast majority of people believe the framework is fairly priced and comes with top-notch support and fast-paced development. As a paid licence holder myself, I can attest to this. More information is available here:
Another factor in the pricing of ServiceStack is the ability to host on a Linux machine rather than a Windows machine. After some calculation on AWS’s “Monthly Bill Calculator“:
The cost of hosting an IIS web service on a t2.small instance is $27.82 per month ($333.84 per year).
The cost of a Linux instance of the same type is $20.50 per month($246 per year) – a saving of $87.84 each year.
Although this is not purely enough to justify the total cost of the Business or even the Indie package, it turns a $299 per month package cost into a $211.16 “True” cost if the developer decides to host on Linux rather than the only other alternative for ServiceStacks competitors – Windows.
The starter package is free, but comes with usage constrictions and can only be used with the previous version of ServiceStack. The usage constrictions are as follows:
- 10 Operations in ServiceStack (i.e. Request DTOs)
- 10 Database Tables in OrmLite
- 10 DynamoDB Tables in PocoDynamo
- 20 Different Types in JSON, JSV and CSV Serializers *
- 20 Different Types in Redis Client Typed APIs
- 6000 requests per hour with the Redis Client
This is enough to build a very small web service, but too restricted for most enterprise developments.
The indie package comes at the cost of $299 per developer and comes with unlimited usage, 12 months of updates and support, an Issue Tracker, Support Forum and a Named Licence (developer only, non-transferable). The named licence restriction signifies that the indie licence is really only an option for startups or people who are 100% going to stay with whatever small company they are with.
The business package is $999 per developer and comes with everything the Indie package comes with, but with the exception of instead of a Named Licence, it’s a Floating Licence (can be transferred when a developer leaves a project). Also it comes with the addition that the owner get direct, private email support from the ServiceStack Developer.
The primary question most developers will ask themselves is why would they chose an third party open source framework over a Microsoft one. Microsoft’s WebAPI has effectively replaced WCF – why would you need something else, especially when using WebAPI is effectively free and ServiceStack costs $1000 for the first year. The answer is that there are a lot of problems with the solutions that are available from Microsoft right now. Some of the main problems that we see is that though the Microsoft frameworks are highly configurable and usable for a variety of different solutions, they come at a cost of:
- over-complexity (Endpoints and formats, Hosting and configuration, Transport, Deal with your own IOC)
- no clearly set out standards enforced
- no cross platform hosting (IIS only)
On top of this, the cross platform support that ServiceStack offers allows it to be run on Linux machines, which opens it up as a viable framework for Web Services on Ubuntu, Chromium, IOS and Android.
ServiceStack is also a much faster framework than its Microsoft competitors (and even its main third-party competitor NancyFx) in terms of end-to-end performance as proved by the Performance section of this article.
Overall I believe ServiceStack to be a very viable alternative to frameworks such as Microsoft WebApi and even NancyFx.