Skip to content
· 58 min watch
Carmel Eve By Carmel Eve Software Engineer II
Jess Panni By Jess Panni Principal I

Explore cloud-first architecture for tackling illegal fishing using Azure, serverless tech & data analytics. Learn design principles & cost benefits.

About this talk

Azure Oxford

Illegal fishing is a worldwide problem which threatens developing nations, damages marine wildlife and supports other criminal activities like human trafficking and slavery. Recently we worked with a not-for-profit who, through machine learning and complex geo-spatial models, detects and helps to tackle this vital global issue. Through Microsoft Azure, we enabled them to more reliably, and in near-real-time, produce fishing alerts from all over the world.

In this talk we will walk through how to construct a cloud-first architecture based on serverless and data analytics technologies. We will then explore the important principles and challenges in designing this kind of solution. Finally, we will see how the architecture we designed through this process not only provides all the benefits of the cloud (reliability, scalability, security), but because of the pay-as-you-go compute model, has a compute cost of less than £10 per month!

Read the transcript

Introduction

Jess Panni: This is a really fascinating talk in the sense that, as you know, as a software consultant, endjin, software consultancy, myself, I've been doing this for quite a number of years now, and it's not often that you come across sort of projects which are sort of interesting from a technical point of view, but actually also interesting from a domain point of view. Something that has a sort of real sort of social and environmental impact. And this is actually one of those, one of the sort of examples here which I think you find rarely, as I say, in sort of software consulting. So really, really excited to talk about this with you today.

So what will we learn? First of all, why, what do we mean by illegal fishing? What is the actual problem we're trying to solve? We're then gonna move on to talking about commodity computing, and in our opinion, why we believe that not all serverless offerings are equal. We'll talk about an approach for building low-cost planetary scale solutions, and the approach is really quite important in terms of how we solve this problem. There's a sort of tagline at the beginning about, you know, processing billions of data points for 10 pounds a month, so the approach was really what enables us to do this.

I'll then hand over to Carmel, who will help talk you through building a proximity detection pipeline, which was a key workload of the system, and is one of the features that get fed into OceanMind's machine learning algorithms, one of many that go through. Those features then get obviously scored and turned into actual illegal fishing alerts. And then we'll talk about lessons learned around benchmarking and optimizing the solutions, and why we feel that it's actually really so important.

Overfishing

So I didn't really appreciate the severity of the issue, actually, I must admit, when I first became involved in the project. And actually learning, getting to know OceanMind, understanding where they're coming from, some of the challenges, was really quite eye-opening. I mean, ultimately, you know, we're in a bad situation. The biodiversity of oceans are, you know, at serious risk due to overfishing.

And if we look at some of the numbers, this first one was really quite surprising to me: three billion people rely on seafood as a source of protein. We often don't actually think about the kind of humanitarian, the social impact it really has on people around the world who rely on seafood as a food source. A third of all fish stocks are no longer biologically sustainable. One in every five fish sold is caught illegally, which is 24 billion dollars worth. And also there's a strong association with illegal fishing and other criminal activities, such as people trafficking, human slavery, illegal salvage. Where there's one, you know, it's said about people, they're usually doing more than one bad thing.

Protecting the world's oceans

So we were really fortunate last year to work with a company called OceanMind. They're actually quite local too. They're based in Harwell, over down the road a little bit, that's ten miles down the road. Their mission is to solve this problem, and they do this by collecting billions of data points in near real-time, applying AI machine learning to those data points to identify illegal fishing. And they collect the outputs of that, and they provide that to law enforcement agencies, to the seafood supply chain as well, so that when people are selling or buying seafood, they know it's coming from a sustainable source.

So yeah, really a really fascinating company. They've got lots of information online. They've been doing lots of talking around their technology and the problem specifically, so if this is an area which you're kind of interested in, I advise, you know, go and Google them, because there's a lot of very good information out there.

This is one of their systems. It's an old graphic, and the reason why I say that is because we had a new graphic of this, and I'm hoping we've got the right page of the day. If not, we'll switch over in a sec. This here actually, every point you can see here is a vessel, an ocean vessel, a marine vessel over a certain size. And every marine going vessel over a certain size is required by law to have equipment on board which broadcasts information about where a vessel is at any given point in time, information about that vessel, the size of the vessel, what it's doing, what its purpose is, really.

And you can see here, actually, fascinating to see the outline of the continents. That's just an outline of where vessels are at any given point in time. Now this kind of screen is actually broadcast on a sort of wall about this size, actually, the whole length of this wall, on lots of screens, on a big version. And it's kind of like their NASA-style sort of Mission Control, where they can go and they can literally have a sort of slider and they can rewind, and they can see what happened, where vessels have been and gone. They can zoom in, they can go and have a look at a particular area, for example, see what's going on in that particular area, and they do analysis at that sort of scale.

They also have applications which their analysts use, and basically they collect all the fishing alerts from their ML algorithms, they correlate that data with observational data, satellite imagery and the likes, and they then sort of validate, quantify it, and then forward that information on to authorities, as I mentioned earlier.

How OceanMind detects illegal fishing

So the way they do this is they collect, as I mentioned, vessel telemetry. They collect satellite imagery. They actually sort of hire satellites out, you know, satellite time. So if there's a particular area of the ocean where they suspect something, you know, suspicious is going on, they'll actually go out, you know, they'll rent some satellite time, they'll take some pictures of the ocean, which is quite important. They use radar imagery as well. They take all these data sources and they push them through a set of geospatial models and machine learning models.

So basically there's a lot of feature engineering that happens upfront, geospatial feature engineering, which takes the raw data, turns them into features that the machine learning algorithms can use to look for specific types of fishing alerts. And they do get, you go down to, you know, the actual individual type of fishing, such as trawling, longline fishing, anything that you can imagine. They can, you know, they can look at the traits to identify, you know, very specific types of fishing.

Fishing alerts, those are the things that get published, and they get exposed through APIs and integrations with systems like the one I've just shown you, or the analyst systems, and now also for public API consumption. So actually, as part of this project, it was a Microsoft funded project as part of the AI for Earth program. So Microsoft put some money into it. Part of that agreement is that OceanMind provide APIs for the community to help get involved, and one of those APIs is an API which allows you to bring your own vessel tracks and all your own data, and it will return the fishing alerts that they detect from those vessel tracks.

The organisational landscape

So, organizational landscape. What I really loved about OceanMind is they're not content just with illegal fishing, okay? They are really driven just to solve any type of environmental, humanitarian challenge, and I already mentioned a few of those earlier. And so part of this project was to take, you know, some of their sort of on-premise systems, which were struggling to scale, take it into Azure, so that they can use the same technology to scale out, not just in terms of their operations, in terms of more real-time kind of workloads, but also to solve some of these new interesting types of challenge, you know, challenges around anything to do with vessels, oceans and data that they can collect.

So part of this particular drive, or the immediate drive, was to get faster, more real-time alerting. The faster you can detect something's going wrong, the more likely you are going to catch somebody in the act and be able to reprimand them, and get the law enforcement agencies to the right place at the right time. They wanted to use more sophisticated AI, and that was a big driver to go on to Azure, in terms of the levels of models that they could potentially start exploiting was obviously greater, and the technology is there that allows them to do a lot more than they could have done on-premise.

They wanted also to expand their remit to collaborate with external parties, as I mentioned earlier, so exposing algorithms through APIs, sharing information with people so they can help a good cause, and everyone hopefully, you know, will benefit as a result. But like any other organization, they've got their constraints. They are a not-for-profit organization, so they're budget constrained. Originally they were running on premise, so they had on-premise servers that were glowing white hot trying to keep up with the data they were trying to process. It was much more of a batch driven system on-premise, cuz that's all they could actually do at that point.

Of course, there's no room to scale, being an on-premise system, and it really truly was an on-premise system. They have servers, and they're like running on premise. They were spending a lot of time tackling fires from infrastructure, servers misbehaving, you know, updating operating systems and the like. And, you know, being a not-for-profit, they've got a small development team. It really is a small development team, so it's about doing, you know, much more with quite a small, you know, set of people. And that was their key kind of drivers and design constraints.

Cloud evolution

The obvious decision, I think, you know, well, you know, I shouldn't be here, I don't think, if we weren't aware of the power of the cloud, so I'm not gonna sort of go on about that so much. But clearly they see cloud as being the key enabler that allows them to get scale, allow them to get the more sophistication they need going forward, and keep the business moving in the direction they require it to.

If we look at cloud evolution, this is not going to come as a surprise, okay? They want to go from on-premise into the cloud. If we look at the cloud evolution, we see infrastructure as a service as a potential offering. We can lift and shift their existing systems as is, if we wanted to. We could re-engineer for PaaS or serverless, but clearly, the more we move to serverless, the more potential we've got for reducing the general amount of operational overhead, hopefully allowing them to innovate more quickly and spend less time worrying about infrastructure. So that's probably not news to most people. If it is, I can talk forever about why it's not.

Commodity computing

But I do want to quickly talk a little bit now about what we mean by serverless, and what I mean by serverless, because I think serverless is being used as a bit of a marketing term by cloud providers, and it's not really doing justice in terms of what it is, in my opinion. So I prefer the term commodity computing when I'm talking about serverless, because it allows us to draw parallels with other types of commodity services we know.

So the electricity that flows into our homes is a commodity service. We're used to it, okay? We've got our laptops plugged in, we charge our phones, we expect to, you know, pay our electricity supplier for the amount of energy we consume, okay? But that's actually, when we think about all the serverless services, even the PaaS services you hear about in Azure, that's not actually always the case. In fact, it's probably the exception, really, unfortunately, in terms of all these services.

As an example, I mean, I know in my house we've recently got an energy meter, okay? And I'm actually... I was a little skeptical, actually, originally. I was kinda like, I don't want that, I don't want the energy board to know what I'm doing when I've got my kettle on, that sort of thing. But actually, since we've had it, it actually has had the desired effect, cuz I do actually look at it quite religiously, and when I put the kettle on, I can see the numbers literally ticking around, okay? And now I've actually started filling up the kettle, you know, just for one cup rather than whole, and that's because of that, okay? So I'm really, really conscious. It's really driving good behaviors, driving down my consumption, and I'm saving money, thankfully.

So, but if we apply cloud computing to that model, we think about, you know, the home. I think it's ten kilowatt hours on average you consume a day, I think was the last time I looked, in terms of the average UK household energy consumption. But if you think about provisioning that, I could say, okay, I'll go to the electric board and say, okay, well, I'll pay you for 10 kilowatt hours every day. They give it you back: there you go, you're getting 10 kilowatt hours. Well, how about that, which is spread out over the day.

But if I put my kettle on, that's two thousand three hundred watts of energy just in that, to boil a kettle, okay? Now, assuming I boil an old kettle, maybe a newer one would be less, but, you know, but if you actually do the sort of arithmetic, you actually realize that's quite a spike, actually. If you look at the average of 10 kilowatt hours, it actually accounts for a spike in terms of the consumption I'm using. And so many cloud services would say, okay, well, you've got to provision for that maximum, you know, that maximum load. So rather than, you know, provisioning 10 kilowatt hours, they'll be provisioning forty six kilowatt hours, I think it all worked out, whatever that might be, which would accommodate for the spikes, okay?

And then you might say, as a response, yeah, that's all very well, Jess, but what about, you know, auto scaling, or scaling, should I say, sorry? We'll give you the ability to scale your electricity. So I've got, you know, a hypothetical little scale. I can slide my meter. I can say, okay, I'll scale up, I'll scale up my energy, and now put the kettle on without it, you know, like fusing or something. I can boil a kettle, and then I can turn it down again. And okay, so I've got some kind of consumption based model going on, which, okay, but let's face it, we always forget to scale down, you know, or we don't realize we scaled up, but we hit the capacity, and either we're not getting the service that I require, or we're getting loads of exceptions. If you're trying to hit Cosmos DB, for example, and it just keeps throwing you back a 429, so that clearly doesn't work particularly well.

But then they might say, okay, well, we can also scale. Rather than you doing it yourself, we can also scale you, and that's also good, right? So, you know, Cosmos DB's got, it's now got auto scale, you didn't know, auto scale pilots coming out, by the way, if you're interested, which allows you to do some level of auto scale. But that's all very well and good, but we'll charge by the hour, okay? So I've also said I'm making a cup of tea, three minutes per cup of tea, but I've got to pay for an hour of that electricity at that level, and that's nonsense, right? But yeah, this is how the cloud charges us, okay? It seems a little bit strange.

So when we talk about commodity computing, what I'm talking about is genuine consumption based pricing. So you're paying for what you use, when you need it, when you want it. The energy is there when you want it, you pay for it, okay? You can consume as much as you want or as little as you want.

Cost comparison

Let's look at some cost comparisons to try and sort of drive this home a little bit. We did some analysis of their existing systems. These are yearly, or annual, costs, okay? We did some analysis before we started. We looked at a lift and shift scenario, you know, if you took all your servers and we put them in the cloud, and we took, you know, we took these over ten years, obviously, if we took the growth rate in which we think that they're going to start accumulating data, and that's why it kind of ramps up. In terms of why it goes up, it's not linear, because the growth rate's going to grow over time. But by the end of year 10, it's gonna be half a million for, you know, for a lift and shift, just an operational cost for the VMs, okay? So yeah, it's quite a bit of money. They're doing quite a lot, to be fair.

When we look at Cosmos DB, now I'm not knocking Cosmos, I love Cosmos, it's a great product, but you can see, actually, we start off year one actually quite... it's quite manageable, 37k. By year ten, it's up to a million, actually. It's over, you know... By the way, lift and shift here is just lifting and shifting. It's not giving them any additional capability, okay? It's lifting and shifting the existing model. This is batch orientated, in terms of once a day kind of processing.

Cosmos DB, the reason why that ramps up a lot more is because we were looking specifically for services that gave us some level of geospatial support, because we're doing some geospatial analysis during feature engineering. Cosmos DB SQL API gives you some level of geospatial support. We looked at that. Cosmos DB SQL supports JSON as payload. JSON is quite a bloated payload format, therefore you see a much more sort of exaggerated ramp up.

And incidentally, when we started this project, don't even tell, it was mostly big. When we started this project, beginning of last year, Cosmos DB had this little hidden charge nobody really knew about, okay? If you had the more... I can't remember what this is right now. I should have had this all set up before, okay, wrong. But based on the amount of data you're storing, Cosmos used to enforce that you had a minimum number of RUs. So if you had started building up big data sets, it required that you ran it at like ten thousand, fifty thousand, you know, a hundred thousand RUs, depending on how big it was, as a minimum. They've actually sort of sneakily, they never talked about it, and they sneakily removed that about, well, maybe six months ago, which is why these numbers were actually lower than what we originally saw, which were actually even more eye watering than that. And that's not particularly eye watering, but they were originally really, really eye watering, but that has gone away now, so don't worry about that.

But what if we could implement the solution using what I would call more commodity based serverless, or certainly services more on the commodity scale, so things like Data Lake Store, Azure Storage, and Azure Functions, Azure Functions being functions as a service, which some people would argue is genuine serverless? But in this argument here, what would that come out at? Clearly these two solutions have a lot more smarts. Let's forget about that for a minute, and we'll explain how we solved those smarts. But if we just look at the costs, and this is based on actual workload tests that we ran through. So this is actually after we hypothesized that we would actually get significant benefits, and as we went through, we started benchmarking what we're doing.

Data Lake Store, in terms of the data that was coming through, comes out at about 260 pounds after year 10 with full data retention. I forgot to mention that, actually: OceanMind have full data retention. They want hot data all the time. They want that, you know, that big, big wall picture of the world. They want to go back, start today and go all the way back 10 years ago if they want to, okay, the live hot path data. So six and a half grand for storage.

Azure Functions starts at fifty pound after the first year, goes up to 290, which is actually nothing, right? It's really nothing, actually. Hopefully, when you see Carmel talk about actually what we're doing in that workload, you'll realize that it really is absolutely nothing. So on paper it works out pretty well. Incidentally, the ten pounds a month: if you didn't have the data retention, it would cost ten pounds a month for compute, which is where that comes from. Is a key lesson Sam has a significant, it's a less, that's what I'm, azimuth came from. But OceanMind want to retain those data, so it does actually go up, as you would expect.

So the problem we have is, how do we fill this gap between a geospatial, customized geospatial solution here, something which is very, very cool and has lots of features, that's why you're paying that money, to something which is much more primitive? But if we can exploit it, the benefits are actually quite significant.

Serverless characteristics

So to summarize the characteristics we're looking at from a serverless point of view: zero administration. We don't want to spend any time doing administration, or as little as possible. Pricing based on consumption. Transparent scaling from zero. We have to pay... in order to take advantage of that, there is this kind of thing we need to be aware of, which is that naturally there will be limits on resources. We can't expect everything, right? These types of environment, certainly the consumption based environments that you see in clouds, typically have limits in terms of memory, limits in terms of the number of outgoing connections, those types of things that we have to be aware of, okay? It's just by definition. We'll talk a little bit about how we manage that as we go through.

We want to provision capacity only when it's needed, and we want the option to do containerized hosting. And the reason why I called this out is because a lot of people say serverless, Kubernetes, and that's the...

It's like, yeah, but we want to take advantage of clever Azure native services, cloud native services, which typically... you can move between clouds. Azure native, because Azure native's going to give us the most value in terms of, you know, if we're happy to bet the farm on Azure, then great. But actually, now, with the likes of Azure Functions, you can run those in containers, so you can actually still have the portability if you want it to, and if you need it to be able to containerize and put more resources behind it, you could.

Incidentally, also, as you're probably or possibly aware, with Azure Functions you do have the provisioned capacity model as well, so you can actually scale it up if you do need the extra horsepower, and there's no option because you're just doing lots of really powerful stuff. You still have that option, right?

Serverless at scale

So serverless at scale. This is pretty obvious, really. When you talk about IoT workloads, you're doing lots and lots of message processing, and we talk about, you know, one and a half billion messages a month that we're processing, vessel telemetry that we're processing. If we're processing each message, if we can make a small optimization on one of those, over billions of messages that can accumulate to an awful lot in savings, or an awful lot in terms of how much it's going to cost you. So actually, small optimizations or small inefficiencies can have a big impact in IoT based work like this. This is very much classed, really, as an IoT workload. In other types of applications, it may not make sense to optimize it, you know, premature optimization and all that, but certainly in IoT, when we're talking about billions of messages, it does make a big difference, and that's something which we need to be aware of.

So let's have a look at a typical pipeline. We've got external providers. AIS is the format of the data which we receive. It's that telemetry format that vessels broadcast. We've got satellite imagery, as I mentioned, that comes in. They're both binary formats. We need to parse that information out into vessel tracks. Vessel tracks just being, this vessel was at this point, at this point, at this point, at this point, so you see where it's been and gone. That feeds into our geospatial and machine learning models, and then we query the output of those models, the fishing alerts, and the vessel tracks themselves, and any intermediate features that may be useful for analysis, through APIs. That's typically the pipeline, and the challenge is, can we do this with Azure Functions and Azure Data Lake Store?

Developing a feature pipeline

So how do we go about this? How do we fill this gap between, you know, primitive services and a complex problem? So the first thing we do when we're thinking about developing a feature pipeline, and by feature I'm talking about going from raw data, binary data, into some sort of features that we can feed into a machine learning model for inference, is that rather than focusing on the data... So lots of people start these projects going, okay, we've got 1.5 billion messages a month, how do we get this into the system? And they just focus on a project just to get data onto the system.

We think about it the other way. We think, okay, yeah, we know we're gonna have to get data on to the system. Let's not worry about that just yet. Let's focus on what the workload is, and we'll work backwards. All right, what is the workload we want to do? And an important workload I showed previously, I mentioned it earlier too, is proximity. On the screen it reads, it says vessels in proximity. All this means is, can we detect where we've got two vessels in close proximity, either close in space to each other at the same time? Are they, you know, interacting in some particular way that's maybe interesting?

So that's what I want to do. Can we detect vessels all around the world, globally, every single vessel around the world, correlating with every other vessel around the world? Are they close together, and how long have they been in contact for? So that's the workload. Well defined, it's actually pretty obvious to understand from a problem point of view. Carmel will explain how we did this in more detail, but that's the problem.

Once we know the problem, we can go and run some experiments to say, okay, well, we think we can solve this in various different ways with Azure Functions. We have the benefit... well, with Azure Functions, you might say, well, we're limited in terms of the amount of functionality we get out of the box, but in some ways, actually, we can play that to our advantage, because it's just a runtime for running .NET code, right? And there are loads of libraries out there which do geospatial, and we can just pick and choose whichever ones we want. So actually, part of the strength behind this architecture is to give us the ability to say, well, yeah, let's see if we can detect vessels however we want to do that.

So once we've defined the algorithms that, you know, tell us whether vessels are in proximity, we can look at it from a point of view of, okay, what's the optimal data structure for our real time processing? How do we want our data laid out, so if we just read from top to bottom, we could easily see which vessels are in proximity, right? So that's the next problem we need to solve. How do we lay out that data so it's easy to read, rather than querying a generic database and saying select blah blah blah from blah blah blah, right, with quite crazy joins and orders and sorts and everything else? Just lay out, what would the ideal format be for every sort of micro batch of data that comes in? What's the ideal format for that data for us to be able to just stream through as quickly as possible, as memory efficient as possible, and produce the alerts we require?

So for example, this says here, it's a bit washed out there, it says vessel coordinates partitioned by time, dot dot. Basically means exactly what it says. We could list out all the vessel coordinates partitioned by time, by some kind of distance-y thing. Carmel will talk about that in a bit. We can then look at data sources. Where's this data coming from? Well, we know we need vessel telemetry in some format, so we can take the same principle. How do we get telemetry into something which can organize that data into the format we require and the layout we require in order to feed this model? Ultimately, of course, we're going to go back to our data provider. Can our data provider provide the data at the frequency we require in order to satisfy our workload requirements, SLA requirements?

So that's the approach we take for every type of problem, and if you scale this out, this is what you see. So we've got our vessels in proximity. We've got a bunch of other features. This isn't the only one, there's lots of them. We have what we call data projections, which are these optimized data structures, you know, that we can quickly just read in, stream in, so their algorithms generate the required features, and then on to our machine learning algorithms. And we've got a common data source, telemetry, feeding those. Now this idea here of data projections is gonna be key in terms of how the solution is going to work, and we're going to go into that in a bit more detail.

What's really interesting about this is, you kind of almost, like, if you stand away from it, you kind of, like, sort of squint a little bit, you've almost kind of got, I suppose, a microservices type kind of approach going on. You've kind of got really well defined, autonomous units of work which solve a problem. They potentially own their own data. It's something they lay out the data however they want. It's... yes, okay, it's coming from a common data source, but it gives you isolation across each individual feature, which allows you to potentially scale out development, allows you to optimize each feature based on their specific workloads. All the stuff which you get from microservices you can apply to analytics as well, and so the approach is very, very similar.

Serverless machine learning

So yeah, what about machine learning? ONNX, the Open Neural Network Exchange, is an open source specification for serializing computation graphs. Why is that important? Because it allows us to train our models and run them in whichever runtime makes sense to our problem, and that may be a serverless runtime. So you've got your usual tools, any tools that you kind of use that can produce an ONNX model. So for example, you could create a TensorFlow model, serialize it out to an ONNX model and run it in Azure Functions, for example, and just do your inference, your scoring, within an Azure Function, which is serverless. Brilliant. You know, a really simple way of working. It separates out the two distinct kind of problems that you're trying to solve: training, retraining, versus inference.

Serverless inference

If Functions doesn't work for you, and it may not... Functions don't support GPUs at the moment, so if you require GPUs for your ML inference, then Functions may not work. But for a lot of scenarios it would. You can drop down to something like Azure Machine Learning service. You can run on virtual machines. You can run on edge devices, however you want to. But you can pick and choose, so ONNX is actually really quite a key enabler for serverless ML workloads.

An experimental method

Before I move on to actually some bit more detail in terms of how it all kind of works, I want to talk about the experimental method. So in data science, we're really trained to... any data scientists in the room, this is drilled into you from the ground up: scientific experimental method, which is to define your success criteria upfront. Define what is success for you, along with your hypothesis. Run an experiment, prove or disprove your hypothesis. If it works, great, move it into production, move on to the next thing. If it doesn't, rethink, try a different set of data, try a different hypothesis.

So for, you know, data scientists, this is second nature to people. As developers doing these types of uncertain types of problems, we didn't know we were going to be able to do this, right? We didn't know that we could run it for ten pounds a month. We had an idea that we'd actually have some significant benefits from this. We didn't know, you know, the optimum algorithms for running this, and the memory thresholds of Azure Functions, et cetera. But we can run it as an experiment.

So for example, can we process 1.5 billion messages per month for less than ten pounds compute costs? Yes or no? So define the experiment, let's run it in the simplest possible form you possibly can, benchmark it, and adapt according to everything you see. And that's the number one golden rule for how you actually develop optimized solutions, really. Don't just make assumptions and just code to assumptions. Prove it.

Demo: exploring the data lake

I just want to show you a quick example of the data. This is kind of like a pre-pre-demo. Carmel will explain how this actually comes to life. But this is Azure Storage Explorer. Actually, Azure Storage Explorer is used in this particular scenario just to show what's in our data lake. Presumably everyone here has some familiarity with Azure Storage, yeah, in terms of what it is? Azure Data Lake Store basically just builds on top of Azure Storage. It provides us with a hierarchical namespace, so we can do more efficient analytical workloads on it.

What you can see here are the file systems that we're using to organize data. So we've got a data file system, that's where most of our data goes into. We've got a raw file system, which was where all the raw data goes into, and we separate that out. We use file systems and use folders as security boundaries in order to make sure that we control who has access to what, and that's really important, especially when you're working with data that may be sensitive.

If we have a look at the data, we've got three folders here. If you've done any kind of pipeline analytics in the past, this kind of probably looks sort of familiar. We've got a parsed folder. The parsed folder contains, if I drill into it, it's gonna let me, contains data which has been parsed from raw format, from our raw binary format. The parsed folder contains the... it contains the data which has been parsed from raw format into a format which we can use for analytical purposes. It doesn't really make sense to parse each file again every time you're doing some analysis. If we can turn that into a format that we can query more reliably or easily, then that'd be better.

We standardized on Parquet, which is the file format. If you want to learn more about that, grab us afterwards, but it has some benefits in terms of how it lays out data on disk, in terms of compression and everything else, which is the reason why we chose it in this particular example. After parsed, we had our projections folder, which is where we took the parsed data and we projected it into representations which were optimized for our analytics. And then we had, which I'd be showing if we were connected to the internet, I'd show you, there's a signals folder, which is where all our alerts went to. These are the signals which our analysts use, including fishing alerts themselves. So we kind of have this kind of standard kind of approach.

Now what I wanted to show you was that all that data's empty, so if we actually went and ran this in a moment, you'll see it populates it. Just to show you there's no smoke and mirrors. We may have to run the video of it.

Proximity algorithm

Carmel Eve: So Jess talked a lot about sort of the approach that we took, so let's try and talk a bit more concretely about what we did. And so what do we need to do to build up this processing pipeline we're talking about? So the one I'm going to focus on is the proximity analysis. So Jess spoke about this a bit, but basically proximity analysis means finding ships which are within a certain distance of each other for a certain amount of time. And it's important because this is one of the factors that OceanMind fed into their machine learning models in order to detect illegal fishing.

So this involved finding these ships in close proximity using their vessel point data. So ships have to check in by law, I think it's about every five minutes, and so you get all this vessel point data, and from that you can build up these vessel tracks, and then you can analyze these tracks by comparing them to one another to find events where two ships are within a certain distance, and then therefore feed these events into the machine learning.

But because we decided to take this sort of serverless approach, so we decided against these out of the box... like, so we could have moved their existing systems on to Azure and then used the geospatial engines they were already using in order to do this analysis, but we were trying to do this in a more serverless sort of way, and build up the exact processing we needed, so we had to do this ourselves.

So that involved taking... so you had one ship, and you had two consecutive vessel points in the track, and so you took the start and end point of that little segment of vessel track and used the average velocity between those two points to work out equations for the position of that vessel in both the x and the y direction. It's actually latitude and longitude, but because of the scales we were working at, we could approximate that this was also planar. We could then use these equations to work out an equation for the distance between two vessels at any given time. So, you know, just by Pythagoras, the square of the distance between these two vessels is just the square of the difference in their position in either of these directions.

So once we have that, we could work out the two times: at which the vessels went within a contact distance of one another, and when they left that distance, and therefore raise events based on how long they spent within that proximity.

Narrowing the candidates with R-trees

So the issue with this sort of analysis we had to do was that comparing all two hundred thousand vessels in the ocean to every other vessel, each of these vessels checked in about every two minutes, so that was like 300 million comparisons a second. So we needed a way of reducing the amount of ships we needed to compare. So we had to find a way to quickly identify candidates for this proximity analysis. So we were looking around for ways to do this, and we were sort of researching geospatial algorithms, and while doing this we came across a paper about R-trees. So R-trees are a way of sort of storing and indexing spatial data.

And so the way we did it was, so talking about these segments of vessel tracks, for each of those little track segments we found the bounding box, and we stored those bounding boxes in a structure like the one shown here. We could then sort of focus in on different parts of this R-tree in order to find bounding boxes which were overlapping, and therefore segments of tracks that were sort of likely to be within a certain distance of one another, and therefore candidates for this proximity analysis. This meant that we could really, really reduce the amount of data that we had to compare, and really reduce the amount of processing we had to do, and therefore the cost of running this.

So, but what we wanted to do is be able to really quickly and efficiently build up these R-trees. So in order to do that, we wanted to store the data in a certain way which would make it easy to just basically read the data out straight into this R-tree. And the way that made sense to do that was to store the data so that you could basically read out the track for each vessel, just like one after another.

So in practice, what that meant was that when new data arrived, we'd partition this up into different time boxes, and this meant that you could sort of just compare each of the tracks to other ones within that time box, and therefore ones that are only, like, you know, within a certain time window of one another. And then for each of those files, you end up sorting the data first by vessel ID, and then for each vessel sorting by timestamp. So like, in this really simple example, we've got the first half of the file would be the track for vessel 1, and the second half would be the track for vessel two. This meant that we could read the data straight out of these vessel tracks and into this R-tree representation, and then get that done really quickly and carry on with the rest of the processing.

Demo: a projection file in Databricks

So just to show you what that actually looks like in practice. So this is a... we use Parquet, as Jess mentioned, which is like a really compact file format. This is shown using Databricks, but, like, Databricks is really great for, like, exploratory analysis, so it's really good for just going, oh, what does my data look like? And it's useful here to show you this Parquet file, because Parquet is a bit of a nightmare to actually visualize.

So, but yes, so we can see here we've got... so this is an ID of a vessel. So we've got the first half of this file, it's the track for vessel one, and the second half, it's the track for vessel two. And we've got a timestamp, and then latitude, longitude, and another ID, and some course over ground, some other data which talks about the vessel track. So, yes.

And the great thing about this is, so this was the representation of the data that was useful for the analysis we wanted to do, so to build up these R-trees. But if we wanted to do a different sort of analysis, we could just project the data into a different format in order to support that other sort of analysis we needed to run. And this is all possible because Azure Data Lake is a really cheap storage option, and so extra projections of the data are of minimal cost. And this is basically multi-indexing the data, but not paying that premium price for multi-indexed storage.

So yeah, so we've got this multistage processing. We've got data arriving. We ingest it in its binary format. We then parse the data into this Parquet file format, and then we run the processing, the geospatial processing we mentioned, in order to then feed the ML algorithms, and then finally query those results in order to carry on with the analysis. So it's quite a lot of stages and processing. We need some way to sort of orchestrate this.

Durable Functions

And that's where Durable Functions came in. So some of you might already know, being Azure Oxford, but Durable Functions are an extension of Azure Functions which are used to sort of build long-running, stateful processing. So in order to do this, you have sort of multi-stage processing, and each stage in the process is calling out to a different async operation. And as you go through the processing, you store state, because you need to be able to restart the processing. Because these are long-running operations, if the host restarts, you need to be able to restart from where you left off, and therefore you store state as you go along.

So yeah, so you build up the processing using these async operations, and you can also control the parallelization within the system. So if you've got processing that can happen in parallel, you can fan out, and sort of more function instances can be started up as you fan out. And then, if you need to aggregate those results and do the analysis over this collection of results, you can fan back in and do that.

So yeah, there's a few different patterns used in building up this long-running orchestration. So function chaining is, if you've got these multiple steps you need to carry out, function chaining means to take the output of one step and use that to feed the execution of the next. So this is how you build up your sort of multistage processing. If you can split up your processing into multiple little stages, you can then orchestrate these using function chaining to build up, like, quite complex processing.

Durable Functions also has inbuilt support for the async HTTP API pattern. So that pattern is basically, if you kick off a long-running operation via an HTTP call, you will then be returned a redirect link, which you can then use to poll for the state of the operation. And Durable Functions really... so it integrates really well with Azure Data Factory, because Azure Data Factory will automatically poll the endpoint for completion. So then, like, once the durable function is completed, you can then carry on with any more processing that you're sort of building around that orchestration.

And I've already mentioned the fan-in, fan-out pattern, so that is, yeah, for controlling parallelization within the system, meaning that you can really speed up the processing. If there's bits that can happen at the same time, you don't need to then run those all in series.

Orchestration

So yes, in practice, what this looked like: so new data arrived, it was parsed, we could then project out. So in, so the projection I was just talking about, where you have the vessel tracks, if you had another projection you wanted to do, you could do those in parallel, because those two projections would be completely independent. And then for each projection, you have the sort of different partition files. Each of those partition files are then again completely independent, so we can then run those in parallel. And then if you sort of need then to aggregate those results and say, okay, overall, what proximity events do we have, you can then fan back in and analyze those events, and then finally query the insight out the other end.

Demo: running the orchestration

So this is where we go to the live demo. I actually might... so I didn't manage to run this live demo last time either, because last time I clicked on, I went, oh, live demo, what could go wrong? Clicked onto Postman, not responding, would not wake back up, and literally I'd clicked on one thing. Anyway, I think I'm going to run the video this time as well, just because the internet in this basement is not incredibly fast. And so usually this all runs up in Azure, but here, because I'm running it locally, I have to download the data and re-upload it, so it's gonna take a while.

All right, so here we've got running locally a durable function. So usually this whole thing would be kicked off when a new file arrives into the system. This would then kick off this durable function. So you have the function input, and that is just sent into here. I'm just running it through Postman. But so we start, we can see it's projecting the vessels for this particular file, and hopefully, so here you can see on the right that it started to read in the data for that file, so you can see the memory spike increase.

And this tool was actually really good as we were running this, because we could see sometimes that the memory spike just, like, went off the charts, and there's like, okay, there's obviously something going on here. And we have these function limits in memory that we needed to be aware of, so a very useful tool if you haven't used it before. But yeah, so you can see here that we're running each of these partitions in... you think I'd videoed this, I wouldn't have a... but anyway, usually each of these are actually happening in series, because throughout these partitions we'd like a continuous track.

So what happens here is, so you have this partition file, and you get all the points in that file. And then, because you need this continuous track, if we just analyze each file completely independently, then you wouldn't have a continuous track for all of them. So we take the final points from this file and we add them to the next one, so that when we do analysis over all the files, you get a sort of continuous view of the tracks throughout.

And you can see here there's quite a lot going on. But once all of these have been processed, we can then start doing the proximity analysis, so building up these R-trees and then running that sort of more in-depth proximity analysis over those. And this is all happening in parallel, so this is fanned out, and if you're running in the cloud, you get multiple function instances doing this. So you see it's quite noisy, because all of this stuff is happening at the same time. But hopefully somewhere in this processing you might be able to see "building an R-tree". I mean, I currently can't see one, but I mean, they're in there, I swear.

But yeah, so you get this processing happening, and it all happens in parallel, and then once all of that is done, we can then fan back in and run the sort of in-depth... we then, out the other side, get these proximity events, and can then feed these into the machine learning algorithms. So hopefully this will finish. And so in the demo that Jess nearly did earlier, if the internet had been working, we would have seen that the files here were empty. They are now no longer empty, and we've got projection files. So this will be for this time file. There's a data taxonomy here that allows us to sort of drill into different time periods. But yeah, so we've got projections, and we've now got signals for each of those time periods, and then can use those for further analysis.

Performance in .NET

Yeah, so we've built up this processing pipeline, and we've got all this in place, and we now need to sort of optimize and benchmark it. So to optimize for a serverless environment, and to do that we needed to benchmark the system, so we needed to be able to check that any change we made was actually an improvement in either cost or performance. And so what I mean by optimizing for a serverless environment is, as Jess was mentioning, there are certain constraints in Azure Functions. So there's constraints on memory, and we needed to make sure we're staying within those memory constraints. And also that the pricing is based on both execution time and memory consumption, so the less time we took and the less memory used within that time, the cheaper it was going to be.

Yeah, so we wanted to be able to make sure that anything we did was actually an improvement, and we wanted to build this benchmarking into our change management within the system. So we built a small tool which was based off of Azure Application Insights, which basically monitored the processing up in Azure and spat out sort of function execution units, which are the cost, basically, for what's running, and a lot of other metrics. And this meant that we could then, using this, assess any change we made.

So in order to be able to optimize in this way, we needed to understand what factors affect performance in .NET. And we're focusing on .NET here because we're building the system using .NET, but in Azure Functions you can use JavaScript, Java, F#, so basically a lot of options. And, like, for optimizing for a serverless environment, these principles will apply to any language you're using. Going to focus on .NET.

So the first factor is obviously the processing logic. If you're doing loads of unnecessary work, clearly it's going to take longer than it needs to. But something that people often overlook is the effects of garbage collection. So garbage collection is the process in .NET of clearing up unused memory, and the way that works is it suspends all processing in order to be able to count the references which are still in use. So obviously, the more garbage collections that are triggered, the less time that will actually be spent on the processing you want to do.

So if we could reduce the number of garbage collections, we could really speed up our processing. So in order to do that, we wanted to cause as few allocations as possible. And also, alongside the fact that this is going to improve performance because of the garbage collector, this is also going to reduce the amount of memory we're using, and therefore the cost of the system as a whole.

Techniques for low allocation compute: list pre-allocation

So we used a few different techniques for this, and the first one I want to talk about is list pre-allocation. So lists in C# are based off of arrays, and arrays are a fixed size when you initialize them. A list abstracts over that, in that you can just keep adding items to a list, but under the covers they are built on arrays. So if you don't give a list a capacity when you initialize it, it defaults to four. And so the list, you can continue adding to it, but the underlying array is a size of four. And so if you then go over that capacity by adding four more items, it will allocate a new array of size eight. So then the old array is then discarded and needs to be cleaned up by the garbage collector.

So this causes a lot of extra work for the garbage collector, and it gets especially bad when you've got really, really big lists. Because, so you've got this massive list of items, and we had quite large lists of items with all of our vessel points, and if you go over the capacity of that list, you suddenly get a list allocated of double that size, and you get these massive spikes in memory. And we ran into this when trying to run these functions. We'd suddenly run out of memory. Like, memory would spike, completely run out of memory, everything would die.

So the way to get around this is to give the list a capacity, initialize the list with a specified capacity of whatever size you need, and this will then eliminate the problem of these massive memory spikes, and reduce the amount of memory you're using normally, because when these big memory spikes happen, you've got a load of memory you're using which is unnecessary.

The next thing we used is actually to not use lists at all, and so we used IEnumerable<T>, so using, like, stream processing, so that we never had to store this entire list in memory. This only works because all the processing we needed to do, we could kind of aggregate as we went, so we didn't actually need to do any whole list operations. We didn't need to store the whole list in memory at any given time. But that meant that we could massively reduce the memory we were using at any moment, because we weren't storing it all at one time, and therefore we were way less likely to run into these out of memory exceptions in the first place.

Reference vs value types

Another important thing to consider is the arguments between reference and value types. So if you use a class in C#, it's a reference type. You get this... a class will use 20 bytes of memory. So this is the eight bytes for the actual data, then you get a four byte pointer to that data, and then eight bytes for the object header that objects on the heap have. This is a 32 bit process. If you instead use structs, which is a value type, the memory for the data is stored actually by the object itself, and you don't get that overhead, and it will just use eight bytes.

So this is where benchmarking came in really important, because I went, okay, I'm trying to reduce the memory, we've got a massive list of vessel data points, and structs are smaller than reference types, so I'm just going to switch them all over. I ended up making things a lot worse, because the issue is, if you start having multiple copies of an object... so with a reference type, each additional copy will just store another reference to that same bit of data on the heap, so each additional object of a class will just store an extra four bytes of data. With the struct, every additional copy gets its own copy of the data, and therefore uses an extra eight bytes.

And you can see that as you start to get more copies of an object, a struct will eventually use more data than a class. And we had lots of copies of the same object, because we were comparing pairs of vessel track segments, so we ended up with a big list of pairs of vessel track segments, and then you end up using a lot more memory, as it turns out, when you make this switch. So yeah, it was really important, the use of the benchmarking tool, because we could see instantly that I had not done the right thing, basically.

Using Span<T>

The last technique I want to talk about is a relatively new addition to C#, which is Span<T>. So spans are a way of indexing into, like, contiguous memory on the heap. So this is an example from Ian Griffiths, who's the guy presenting next month. It is his new book on C# 8, and it's an example from it which I have stolen. I did ask him.

So say you had a string that represented a URI. And so if you initialize a new URI object, you can access different parts of that string using the properties on the URI. And the issue is that each of these properties equates to another string which has been allocated on the heap. So you end up with a lot of extra allocations from just sort of initializing this object, which you can then index into the different properties. If you instead use a span to just index into the first four characters, which you know is the scheme, because spans are ref structs, they're actually allocated on the stack, so you don't end up using any extra memory on the heap in order to do the processing like this.

So obviously, processing like this, there's a lot of extra complication. It can be, like, headaches, processing like this. But in this case of serverless processing, especially with big data, as Jess was saying, these really tiny allocations can have a massive impact if you're doing this over and over again. So processing like this can be, like, integral to getting a solution which is cost effective and also highly performant. Yeah, so we used these techniques, and in doing all of this, massively reduced the amount of memory we were using, massively improved the performance of the system, and ended up with something that was costing, as Jess showed, less than ten pounds a month.

Takeaways

Jess Panni: So let's quickly go through and summarize the takeaways before we finish up. So commodity cloud services have really helped OceanMind process more data in near real-time, and ultimately reduce the operational overheads. The constraints that Carmel mentioned in terms of memory, they need to be managed through experimentation and benchmarking. We always knew that our goal was to use consumption based plans for Functions. We always knew we could always go up to the premium tiers if we want to, and we still can if we want to. But ultimately, as long as you go through a methodical process, it's actually quite quick to actually just iterate over, measure what your change has made in terms of overall impact to the workload, and you should be good. Take that into your development processes, is the message.

Cheap cloud storage can be a good alternative to generic analytical databases if you treat it in the right way. The projection approach works really well for this project. We found it works really well for a lot of things. Sometimes databases obviously have their place, and I'm not saying get away from them completely, but, you know, consider whether your workloads would actually map quite nicely to just simple cloud storage, using the data projection architecture that Carmel explained earlier.

References

This is us. By all means, you know, connect if you want to talk about any of this any further. We'll be hanging around afterwards as well for a short time. This is a link to a book plug, so it's Ian Griffiths', only just been released. Recommend you look at it. It's got all the latest C# 8 features, a lot of things that Carmel mentioned in more detail.

Okay, a couple of references for you. We benchmarked and tried to use a, you know, a number of AIS parsers that were out there, open-source AIS parsers. We found that performance wise they weren't brilliant, so we wrote our own. It doesn't support the full set of message types that you get from AIS, but it supports a good set of them. This particular parser can process seven million AIS records per second on a single core, so it's pretty fast. You can scale that out, obviously. So if you're doing any AIS processing and want to contribute, please get involved, just raise a PR. Or if you're just interested in some of the techniques that Carmel mentioned, especially things around Span<T>, that's used extensively in that to keep garbage collection down.

Carmel's done a lot of blogging around this subject, so if you want to have more of a deep dive into some of the things we've just been talking about, there's a few of Carmel's blogs. The R-tree paper, there's an actual paper here. It's part of the RX spatial library as well, if you want to look at that, and there's... follow the links to know more about R-trees.

Microsoft have done some case studies with OceanMind. They're on YouTube, so please, if you're interested in OceanMind, you know, I recommend you get to know them. They're a really friendly bunch. Have a look at some of the Microsoft case studies online.

Finally, we've put together, if you're interested in Wardley mapping... Wardley mapping is a really interesting technique for coming up with the strategy around what technologies make sense to adopt, where to focus your effort for your particular business, when to use commodity services versus building your own. If you've done any Wardley mapping, I thoroughly recommend you have a look at this link. If you haven't done any Wardley mapping, you've heard about it, you want to learn some more, I recommend you look at that link. And I recommend you look at that link anyway, because you'll learn some really good stuff. It's a video online. Please have a look at it. It's really good.

About the presenters

Carmel Eve

Software Engineer II

Carmel Eve

Carmel is a software engineer and LinkedIn Learning instructor. She worked at endjin from 2016 to 2021, focused on delivering cloud-first solutions to a variety of problems. These included highly performant serverless architectures, web applications, reporting and insight pipelines, and data analytics engines. After a three-year career break spent travelling around the world, she rejoined endjin in 2024.

Carmel has written many blog posts covering a huge range of topics, including deconstructing Rx operators, agile estimation and planning and mental well-being and managing remote working.

Carmel has released two courses on LinkedIn Learning - one on the Az-204 exam (developing solutions for Microsoft Azure) and one on Azure Data Lake. She has also spoken at NDC, APISpecs, and SQLBits, covering a range of topics from reactive big-data processing to secure Azure architectures.

She is passionate about diversity and inclusivity in tech. She spent two years as a STEM ambassador in her local community and taking part in a local mentorship scheme. Through this work she hopes to be a part of positive change in the industry.

Carmel won "Apprentice Engineer of the Year" at the Computing Rising Star Awards 2019.

Jess Panni

Principal I

Jess Panni

Jess has over 25 years' experience helping companies succeed through the smart use of technology. He spent most of his career working for leading Microsoft partners across the UK and Australia and was Principal at endjin, working with clients to envision and execute disciplined innovation programmes.

Jess worked at endjin between 2015-2020.