⭐ If you would like to buy me a coffee, well thank you very much that is mega kind! : https://www.buymeacoffee.com/honeyvig Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Friday, November 7, 2025

Creating a .NET 5 Microservice

 

0:00

microservices are an increasingly popular software architecture style that structures applications as a

0:05

collection of highly maintainable loosely coupled and independent services each typically owned by a small team

0:13

if you are wondering if you can use the.net platform to build microservices or if you have perhaps been asked to

0:20

start building them in your company it is worth checking out the multiple existing and new features

0:25

that that net5 offers today and that you can use to your advantage as you drive towards building resilient

0:32

microservices with a minimal amount of code so let's get started in this video you will

0:40

learn how to create a.net 5 microservice from scratch

0:46

how to build and debug a.net5 project in visual studio code how to interact with your microservice

0:52

endpoints via open api and postman how to keep a configuration

0:58

and secrets separate from your service code how to simplify your http requests to

1:04

external endpoints how to deal with transient errors on external services

1:10

how to report the health of the service and its dependencies and how to produce logs suited for a

1:16

micro service environment

1:21

to follow this video step by step you will need a few things first the net sdk which includes

1:29

all the tools required to build your.net 5 apps

1:34

visual studio code which we will use as our code editor so to edit build and

1:40

debug our service postman which is a very handy tool to

1:46

interact with the service endpoints and finally some basic understanding of the c-sharp language

1:54

to get started we are going to use the.net cli or command line interface for this i will

2:00

be using the windows terminal but feel free to use a simple command prompt powershell window

2:06

or whichever terminal you are mostly comfortable with and then being in the terminal what we

2:13

can do to create our micro service project is actually use the web api template so to do that let's do net new web api

2:23

hello net5 that's going to be our output directory and then i'm also going to specify the

2:28

no https flag now the reason to disable https with this flag

2:34

is to keep things simple and also because in a micro service architecture ssl is a concern usually delegated to

2:40

infrastructure components like an api gateway so that the microservice can safely avoid dealing with it

2:46

however feel free to skip the no https flag if you rather use https from the start

2:52

so i'm going to hit enter here and that's going to generate our files for our project

2:58

so i'm going to just switch there and now i'm going to be switching to

3:03

visual studio code to do that i'll just type code dot

3:10

and here we are in the visual studio code interface now the first thing the visual studio code usually do in as soon as you start

3:17

one of these dotnet projects is to offer you to add a few files and we're going to say yes and we're

3:23

going to explore what those files are about this file here describes how visual studio code is going to

3:29

run a series of tasks for us for for whichever task we need to execute here and the main one is going to be the

3:35

build task so this says here okay so we are going to have a task called build that's going to run the dotnet command

3:41

uh which is a process and the argument for that command are so it's build because dotnet build and then here's the project

3:48

that you have to build and then here's a couple of other properties that you want to pass to the building gene

3:54

the other thing that i wanted to mention is launch.json so this is the this is the file that describes really

3:59

how we're going to launch uh this project from the vs visual studio code perspective

4:05

and what this describes is that uh the pre-launch task for for for launch

4:10

is built which is the one that we just saw here you see we said build so we have to anytime you're going to

4:16

launch this project you first have to build it and then you're going to be running the the program that's up

4:22

over here so this is the location where our dll will be generated and also when uh when the host is ready

4:30

when it says yeah i'm ready to go uh this is uh it is supposed to open a browser

4:35

uh so that it browses to the location of the host this is well also where we describe the the asp.net core environment the

4:42

where we are in right now so this is why it knows that we are in development environment and not in production so now that we have done that what we

4:48

can try doing is first let's build this project and you can do that by going to terminal

4:53

run build task built so this opens the integrated terminal in visual studio code

5:00

and boom it has been built and now that it's filled uh we can go ahead and run it so to run

5:06

it uh i'm going to click here i'm going to say start debugging in this debug hub

5:14

to see better perhaps i can expand it yeah then the core launch so just run this

5:22

it's going to build it and now we're opening the browser and

5:28

here we are now the default url that we have configured right now read is not pointing anywhere so if you want

5:34

to actually see something what you can try is just going to the swagger url and this is going to take you to the

5:40

swagger ui or the or the open api specification that we talked about before so here is where you can start

5:47

uh testing your api so if you click let's say on get is the

5:52

only thing that we have defined so far so get for weather forecast

5:58

here you can see a description of this api and you can actually try it out you click here i just hit execute

6:06

you're going to see that swagger swagger ui uh and generates a comma that will be

6:11

needed here's the request url and here's the what the output that we got as you can see it's just a

6:18

simulated objects based on what we have right now in the controller

6:25

now one thing uh one kind of a tip that i have in this case i'm just going to close this is uh how do we

6:32

build this uh more quicker for future iterations uh like one thing to consider is that

6:38

you can just do ctrl shift b uh to open this this build task window

6:43

here right so that speeds up things a bit uh but to really

6:48

make it even easier what you can do is in uh let's go back to

6:56

uh that's adjacent here you can add just a little segment here just three lines i think uh

7:04

which is uh the group so this grouping field here allows us to specify that this is

7:09

going to be the default task so build becomes a default task when you do the uh when you do the you run the

7:17

build test from the terminal menus if you say now terminal and run build task it will go ahead and just build it will not pop up the build

7:23

window anymore and if you do ctrl shift b the same thing would just go ahead and build

7:30

okay now you notice that when we started the project it did not just go to the swagger page it actually had

7:36

trouble getting there and this is and that is why we're missing a little bit of a configuration

7:42

here in sorry launch settings launch.json so here i'm going to close

7:48

this and so in order to tell visual studio code where you want to start when you launch

7:56

you just have to add this uri format section here in server ready action where we're saying that wherever the

8:03

whole support it is just append a slash swagger to the url and that will that will be

8:10

good enough so again we go to the backhop and you click here you can also use type f5 by the way

8:15

and will be the same thing now we run opposite browser and we are right there

8:21

in the swagger ui so now this is this is nice uh to try

8:27

out the the apis uh but eventually i uh find that uh there's uh other tooling that it can

8:34

become uh pretty much more handy uh to test the apis and this is because you may not want to be open in a browser every

8:40

single time that you just change the code in your app so to do that let's open up the postman

8:48

the postman program

8:54

so here we are in postman and like i said pogba is a tool that you can use to query any api that you have available

8:59

really anywhere so what i'm going to do is just go back to the browser and let's remember what which was

9:08

that um that url just hit execute again here it is this is the request url so

9:14

i'm just going to take that and i'm going to create a new request in postman a get request

9:20

i'll just put my url and i'll hit send and as you can see we have the

9:28

the response right here so the nice thing about postman is that we will be able to start creating a bunch of

9:33

requests here without having to worry about opening browsers to test the apis

9:40

and if you're going to do that let me actually just stop this what we may want to do is just

9:46

to actually prevent opening browsers all the time so i'm just going to be i'll just remove this from here so no

9:53

more browsers open for vs code i'll hit f5 the only thing that i'm going to get is

9:59

this prompt here that says yeah we're listening in that port but then i can just switch postman hit

10:05

send and now we get my results so i will not be dealing with browsers anymore since i'm working on a microservice

10:12

web api kind anyways so to make things a bit more interesting

10:17

and since we're trying to create a microservice and want to showcase a few of the nice things that we have available now

10:22

with dotnet5 what i thought we could do is just bring this project a little bit more into reality

10:30

so what if we can just change this project and make it actually query some weather information

10:35

uh perhaps from some external service so that we can actually tell the weather of some city right uh so to

10:41

do that what we can do is just take advantage of a service called open weather so i'm

10:47

going to go to this page now it's called

10:53

openweathermap.org and here sure let's allow location

11:05

this service allows you to query a bunch of apis several of them that are free

11:12

but you can use just query query weather data so for instance if we go to this api here

11:18

you can see that you can use this to create the weather to create the weather for some city and as long as you have a an

11:25

api key available so the api key is the way that the service identifies you

11:30

so the first thing that we're going to need here is to actually get an api key so to do that i'm going

11:37

to hit there uh here is where you're going to need to create an account it's it's totally free

11:42

and i already created mine so i'm going to go to my account

11:50

all right there it is and uh you will get i think you'll get a

11:57

one key by default this is what i found the first time that i came here but you can create as many api keys as as you

12:03

need so i'm going to copy my api key actually not copied yet uh let's let's look back

12:10

at the api over here uh so let's actually test out this api uh since we have postman

12:16

available how would this api look like so i'm going to go back

12:21

to our page i'm just going to close swagger i'm actually also going to stop this code and i'm

12:28

going to go back to postman so i'm going to open another tab here and i'm just going to paste what we just

12:34

found and then i'm going to put https here this is an 80 ps api

12:41

and uh we want to query data for some city one of the closest cities to me a

12:46

very nice city very nice city is seattle so let's do seattle and here's where you will paste that

12:52

api key so i'm going to go back to the open weather page i'm going to copy this api key

12:59

and i'm going to paste it right here and then i'm going to be hitting sent

13:07

and here it is we have some

13:14

information about the weather of seattle as of right now and they're really the most meaningful

13:19

pieces here are this kind of a description of the of the

13:25

weather and not surprisingly it's raining in seattle um then we have the temperature

13:31

and this temperature is actually in a bit of a different measurement that you would expect so

13:37

what we're going to do is just change this little bit so that we can append

13:45

units equals metric so that's going to give us the weather in celsius

13:50

uh let me hit send let's see yep that makes sense

13:56

it's pretty pretty cool right now around here and we're choosing celsius just because

14:03

uh to play around with that with these objects that are already been generated for weather in the in that project right and the last one that we're going

14:10

to pay attention here is the dt which represents the current time

14:16

i mean or the time of the calculation of this weather information

14:21

okay so now that we have this how do we integrate uh how do we call this api from our from our microservice

14:27

so to do that let's go back to the project uh the first thing that we're going to need

14:33

is to actually specify i mean there are two interesting pieces from the name that api

14:38

which are uh the endpoint i mean the location of this api that we need to call and the other

14:45

interesting piece is going to be the the api key so this we are going to

14:50

treat as configuration as you should do in any microservice you should not just hard code these pieces of data

14:56

you want to set it in such a way that you could change them anyway without having to really touch

15:02

the application so how can we bring that in let's go back to the

15:08

project i'm just actually going to close all this stuff and what we're going to do is we're going to create a a class

15:15

that's going to represent that information in the project so to do that i'm just going to say

15:22

new file and we're going to call this service settings

15:28

so let's put just let's put it in the same space as everything else which would be

15:34

hello.5 and let's do a our class which is named service

15:40

settings and here we're going to add uh a couple of properties

15:45

right the first property is going to be uh

15:52

let's call it open weather host and let's add a second one called

16:00

uh api key okay so we have these two

16:07

properties now uh and yeah so this is going to represent the host uh just

16:14

api openwaremap.org and the other one's going to represent the key now how do we let's look first at the

16:22

host so open weather host so this is something that we should be able to safely configure

16:27

for our application outside of the of the actual code uh so that's where we can actually take advantage of app

16:33

settings json so what i'm going to do is just add one section here

16:39

we should have ideally should have the same name of this service settings class so i'm just going to

16:45

copy this so we're going to call it service okay

16:54

and here we are going to have uh those same two pro well actually just open

17:00

water host we don't want to put an api key here and yeah you could but we don't want to

17:06

store secrets over here that's kind of a bad practice so the host is going to be

17:12

like we said api openwaremap.org and that's going to be our configuration

17:21

for the host now what do we do about the key so we don't want to just type it here so you should never ever

17:28

type or hard code a lever and even worse checking secrets into your git repository so to

17:35

avoid that what we can do is take advantage of this thing called the net secret manager so this is a tool

17:41

that you can use to safely store secrets in just for your development purposes not for anything out of your box

17:47

and we'll just keep the secrets outside of the completely outside of the project but still be available for for your app

17:54

when you run it in order to do that let me actually open the terminal

17:59

open the terminal here this is a partial terminal and what i'm going to do is first what

18:05

we have to do is do dotnet a user secrets init

18:12

so this initializes secrets for this project and if you actually go back to

18:18

the project you're going to see that we have a user secret id this was just added

18:23

represents the identifier of the secrets of this project now that we have that what we can do is

18:31

dotnet user secrets set and here we have to

18:39

name the secret that we want we i mean we get a name and a value the name should be in such a way that it

18:47

matches the class that we've been preparing for this in this case we create we created this class called service settings

18:52

so we'll name it service settings we'll do a colon and then we'll do api key

18:59

so this is a way to set a configuration based on the convention that.net knows

19:04

about so for this hierarchy where we have several settings an api key and we can totally configure a a

19:12

set configuration named as service settings called api key and if we had even more nesting

19:17

here like if the api key was a compound property and it has even more properties you could just keep adding columns here

19:23

for keep to keep nesting uh these secrets now that's the key and

19:29

then let's get the value for that so let's get that from postman

19:35

in this case yep that should be our bi key

19:42

here hit enter and now the secret has been stored uh in the in the secret store right so

19:49

it has nothing to do with the project at this point is just store somewhere in the box

19:55

i'm going to close this terminal here so now what we want to do is to tell

20:03

the to tell our app how to register these secrets

20:10

into it and for that we're going to do exactly that so we're going to register

20:16

that configuration that you can do by again using the services collection in startup configure

20:22

services so you can say services configure and here you are going to specify the

20:29

type that we created service settings

20:34

and then just to keep this thing simple we're going to say okay so now from the configuration object

20:39

this is the configuration property that we have right here from that object get the section named

20:47

just same as the class so the class is uh service settings just find a section that's named as

20:54

service settings which happens to be the section that we declare here service settings that's why it's good to

20:59

keep the same name so just by doing this we have uh i mean as soon as the app

21:05

loads uh the configuration engine we're going it's going to find configurations both in app settings json

21:12

and in the secret store uh that are going to be a populated into an instance of service settings

21:19

that's going to be registered here in the dependency injection engine of of

21:25

the net 5. so by doing this we are going to be able to access this configuration anywhere we

21:30

need it in the application which is printed now how where do we actually write the code to

21:37

access the api so to do that what we can do is create a what we call a client a service

21:46

client this is something supported by the i http client factory uh

21:51

object objects internet five and what we're going to do is just

21:58

create a brand new file here we're going to call weatherclient

22:08

same namespace and then we're going to create the class

22:15

weather climb now here in weather client we're going to need a couple of things and at this

22:20

point i'm actually going to start copy pasting a few a bit of more code to avoid so much typing here

22:27

two things an http client object and the service as every setting subject and i'm actually going to bring name

22:34

spaces here http client is the object kind of the key object that you would use in any

22:39

net app to access external endpoints right like the one that we need to call right now so we are going to need those

22:46

two properties also yeah like i said a settings instance where we're going to retrieve this settings information

22:52

now we're going to add is a constructor in this case uh yeah with

22:58

our client and again here we are doing dependency injection right

23:03

so we are injecting an instance of http client that's going to come somehow is going to be constructor

23:09

constructed in startup and is going to be available for us over here without us having to worry about

23:14

how to build it and also this i options object which is how you are able to receive the

23:21

configuration that has been registered right here so we here we configure service settings now we receive a iop we receive an

23:27

ioptions instance here of type service settings which by the way i'm going to

23:34

add a new space and then we just grab both of them into our

23:40

properties http client options has a property called value and value is the one that actually has the

23:46

service settings that we care about next thing to do is to uh have some sort of

23:53

representation or type representation of that api that we saw before so i'm going back to postman here and here

23:59

we can see sorry we can see that if we wanted to get those elements that we talked about we

24:05

would at least before.net 5 we will need to create a bunch of types since you see there's a

24:11

bunch of quite a bit of composition here so it's not just a flat object so we need some weather object here

24:16

which will have description and the description that we are inserted in we will need this main

24:22

a class with the temperature and then we would need yeah just a property for the or a field

24:28

for the for the time uh so yeah before than the five you will need to create at least a couple of

24:34

classes or or two or three classes for all this stuff but luckily in 205 there's this new thing called

24:40

record types so record types is a new way for you to declare this kind of

24:46

objects in a kind of an immutable way and with with a nice addition of how you can compare

24:54

these objects not by reference but by value but it also has a very nice syntax that can simplify

24:59

a bunch of scenarios like in this case instead of having to create a bunch of classes here's what we can do

25:04

so first we know that we need a weather class so let's see we well we need a weather

25:12

object right where we need to have a description inside it all we can do is just say all right so

25:18

i'm going to declare a record the record type

25:24

we're going to name weather and that weather is going to have a description and that's it

25:31

that represents that entire weather object or that weather section that we

25:37

have here okay and which by the way is an array is not just one object but we will need

25:43

instances of where next one is main so from main we will need a property named temp

25:51

so to do that let's go back here and just like we did with weather let's declare public record

25:58

main so like like we said we need a temperature we will use decimal for this

26:05

so decimal called and just like that we now have uh we have

26:11

that main structure right there as a record finally uh we're going to create our overall uh

26:19

a record that has all the properties so let's call it let's just call it

26:25

forecast for lack of a better name and this forecast just like we saw needs

26:32

to have a collection of weather objects an array of wired objects the main object and the the time

26:40

so let's see we're going to say okay so this is a wet array

26:45

we need an instance of main and let's use long for that date time

26:53

and that's it so here's the entire representation of the of the interesting pieces for us

26:59

from that response of the api so no need to create a bunch of classes for this anymore

27:05

now where do we actually do the call where do we retrieve that weather information so to

27:11

do that we're going to just introduce a new method let's call it and i'm going to do a bit of copy

27:16

pasting here so this is going to be an amazing method

27:22

and i'm going to import a few missing a spaces here i guess just one mini space uh async

27:30

method called get current weather async is going to receive a city so we pride a city and it should return one of these

27:36

forecast objects and in order to be able to actually do the query what we're going

27:41

to say is uh so let's see forecast is going to be

27:48

a we're going to use the http client object and um interestingly in starting with

27:54

net5 we now have very handy methods for both retrieving information we're

28:01

retrieving and posting information but also doing the serialization and deserialization for us in a very nice way

28:06

so we just need to do in this case get from sorry get from

28:13

json async and i'm going to add a missing name space here systemnet http so this is the

28:19

the namespace that has the new additions in.5 for this kind of query and here's where

28:24

we would paste the actual url right so i'm going to grab that url from from here

28:33

i'm going to paste it here yeah all hardcore now

28:40

how do we fix this so let's first we have to wait on this because it's an async call

28:50

okay now next thing we're missing here of

28:55

course is the type so what are we going to deserialize into in this case it is a forecast object the one that well a forecast

29:03

record object record type and now here we just have to do a bunch of replacements because we do

29:09

have that settings object just waiting for us over there we're going to do is do a little

29:15

bit of a string interpolation so that we can introduce uh whatever is is

29:20

should be parametrized here just going to open curly braces here i'm going to say so this is services

29:27

it is sorry it is uh what's the name settings just settings settings that

29:35

open weather host and then the other piece is here we don't want to use hardcode cd

29:42

we want to use the city parameter and for the app id

29:49

we want to switch to dot api key and then we leave the meta

29:56

units as asthmatic that's just fine so with that we should be able to just

30:02

retrieve that forecast information just one line uh simplified by the additions in 2.05

30:08

and so after having that forecast object we can just do

30:13

return return forecast and that's it we have a winner client

30:20

that is able to go ahead and retrieve weather information based on some city now

30:26

just as with anything else this was reclined and needs to be registered into the series of services

30:33

available in our application so to do that we're going to go back to startup

30:38

and in startup we are going to go to configure services and we just have to say

30:46

services.httpclient i will say weather client

30:52

and that's it so that will take care of registering the this r class into the services

30:57

collection and that net five will know that it needs to inject an http client object into that class so

31:04

that we can do the actual calls to the other service

31:09

now that we have this uh well it's time to actually touch our controller and to make it a

31:14

real controller that can actually receive a city and return the weather for that city so to do that

31:21

we're going to do just a few things first let's get rid of all these run the random set of summaries

31:29

we're going to need to again inject an instance of that weather client so whether client

31:38

client here it is and then let's let's use a little bit of

31:44

intelligence here create an assign field client so that's going to go ahead and just generate you see generated a private field for me

31:52

and assign it from the client parameter right there ah yeah one thing

31:57

we're missing here is the

32:02

the access modifier so this should be public so we can actually use it on the on the other side

32:11

and we're missing one more thing service settings should be also let's

32:19

forgot that there it is okay so going back to the

32:24

controller now we have our client available and now we're going to change this get method here

32:36

so that first thing is that we're going to modify the route so so we're going to add here uh

32:44

where is it uh route attribute and we're going to say

32:50

that we're going to receive here uh sorry let me just copy that one over

32:56

there keep it simple

33:01

and we're going to receive a parameter here that's going to be the c so now we're modifying it in such a

33:08

way that we're saying hey so the route is not just going to be a wetter and now you're expected to

33:14

provide some city here like i say cl right that's going to be part of the route right so we're just

33:21

kind of describing how we want to our route to look like and then that city we're going to receive here

33:29

okay now we're not going to be returning a list of weather forecast anymore it's just one forecast for the current

33:35

forecast for the city that has been specified

33:40

and now uh yeah we can remove all this stuff and what we can do is say so

33:47

forecast bar forecast say equals um actually we have to turn this

33:54

into an async method because we're going to be calling another using method so this is an async task of weather

34:02

forecast so we have to say await and then we have

34:07

our client so we'll say client dot get golden weather async

34:13

and we'll give the city that should give us the forecast and

34:19

then finally what we have to do is to turn this forecast object that we got here

34:25

which is really a record object into the weather forecast dto that the app is already using so to

34:31

do that let's use to return new weather forecast and then we'll do

34:41

so the summary is going to be forecast that

34:47

winners let's take a closer look at this uh so says weathers here but it's really

34:52

just uh one weather object so i'm just going to rename to weather that's how

34:58

it shows here even if it's an array it's just named weather so we have to

35:03

honor that so i'm going to say where there of that collection we want

35:09

index 0 and from that one we use one description next one is the temperature in

35:14

centigrade it's going to be forecast main temp

35:20

although we have to convert this into an int to match into that contract that we have

35:26

and finally the date that date is actually in a kind of is kind of a unix-based

35:31

time set so what we're going to do is uh data the time of set

35:38

from unix time seconds forecast t

35:46

dot day time uh time yeah that should do it

35:53

yep so let's see are we missing something

36:00

that so let's try to build this um it builds i'm going to do f5 here

36:10

to run it and so it starts now let's let's go back to postman and

36:16

so we're going back to our api it is not anymore just weather forecast we have to specify the city right so let's

36:22

again let's do the seattle sample here see what happens

36:29

boom here it is yeah still very cold in seattle so but yeah i mean we we got it i mean

36:35

we are going we go ahead as soon as and in fact we can explore that a little bit of a

36:40

breakpoint to make it more interesting i'll put a breakpoint right here

36:47

and so we keep going through this method so let's see

36:54

cursor yeah come here we got the weather object and

37:02

let's put a breakpoint back in the controller over here i'll just do f5 so we come back here we

37:08

have the weather forecast object and then then we just do the transformation and we return that weather forecast object over here

37:17

and so that worked that's that's great now one of the things about microservices is

37:22

that we want to make sure that they are reliable so as reliable as they can all the time and as by introducing this

37:30

external dependency uh this weather open weather service uh now we have kind of a point of failure so what

37:36

happens if that service goes down so what does what does that mean for our service can we keep up our availability there

37:43

so let's see what happens what am i going to do here uh it's pretty much the only way that i

37:49

know to test this scenario is to just disable my internet temporarily

37:56

and i'm going to hit send again see what happens uh yeah after i have a breakpoint i'm

38:02

going to remove these breakpoints now hit run

38:07

and boom no such host is known so yeah we can't talk to it there's no internet so now our service is down

38:14

so this is exactly what we don't want to have an error to our microservices so one way to start dealing with this uh

38:21

one first approach we can do is well let's do some retries because it potentially can be a transient issue

38:27

which happens all the time in the cloud so how can we introduce some retries to this

38:33

so let's go back first i'm going to re-enable i call it the internet because we'll need it for the next step

38:40

and i'm going to go back to our app so i'm going to stop it

38:46

so what i'm going to do now is i'm actually just going to close all this stuff go back to the project and actually

38:51

going to go to open the terminal and i'm going to up add a new nuget package

38:57

so to add a nuget package to your project you have to say net package and in this case it's called

39:05

microsoft extensions http poly so poly is a pretty popular

39:12

package has been around for a while and it allows you to do a bunch of a transient

39:19

error policies where you can specify how you want these errors to be handled and to do

39:26

that what we're going to do is go back to startup so we don't have to actually modify the entire uh

39:32

project to do retries here and there i mean like you could say you could think that you may need to go to weather client and do

39:39

some sort of retry here what if this guy fails so try catch and stuff like that but actually we can keep things simpler than

39:45

that what we're going to do is this

39:51

so let's see just copy pasting again yeah

39:58

so add transient http error policy

40:03

uh we are appending this to our http client class this is a facility of the a i

40:10

um what was the name the ihtp client

40:16

builder uh where we can introduce a policy so i'm going to actually fix this using poly

40:24

so we have the writing spaces yes so this is a transient error policy where

40:29

we or we are saying that the policy is a wait and retry policy

40:34

is going to retry 10 times so that's the police let's retry it 10

40:40

times and let's see on each retry attempt it is

40:46

going to sleep as much as what this expression specifies now this is what we call

40:52

exponential back off in this case it means that the first time it is going to uh

40:58

it is going to slip for uh two uh reset to retry attempt seconds so

41:04

retry time is going to be one first time is just one so two raise it at a one so if that after that retry we fail

41:11

again i mean after that sleep will fail again and then we're going to wait two raised

41:16

at two right and then two raised at three two raised at four so it's exponential so each time we uh

41:23

wait a little bit more and this is just to add a little bit of uh uh i mean changing behavior to those retries so

41:30

just not keep retrying at the very same interval every single time uh potentially overwhelming the

41:35

service the services is on the other side so let's give it a shot so this should

41:41

allow us to do some retries so what i'm going to do is again disable network

41:48

and run this f5

41:54

so back here i'm going to hit send just waiting there it's not just failing

41:59

now and as you can see if i can expand this uh we're trying so

42:05

we're doing a get we did already two gets here get get and they will probably come

42:11

more gets you see get get get just it just keeps trying just expands the the sleep the sleep seconds a bit more

42:18

and a bit more and if i just fix my network connection now so i'll enable this

42:25

yeah it may take a little bit but eventually we should get a successful lighting it

42:30

already did it let's go back to postman so yeah there it is success so without having to touch

42:36

really any anything other than that little piece in startup over here now we have retries for our

42:44

microserves which is pretty neat now the other thing to consider

42:49

is that so that's nice but what if the services is really going

42:56

to be down for a while and we don't know and we don't want to be really

43:01

overwhelming that other service and just having our clients wait forever and there so to for that there's this other

43:08

technique called the circuit breaker and that i want to show you here so i'm going to stop this

43:14

and the secret breaker is going to allow us to uh introduce a behavior so that we will

43:19

only retry so many times after which we do something that we call the open the circuit and then no more

43:25

uh tries are going to keep happening until some other condition happens so in this case

43:30

let me just add this uh let's see just appending to the same

43:38

sentence so one more transit a transient http error policy called circuit breaker

43:46

so this means that uh we will try we will allow it to retry

43:53

yeah three times so we will retry it three times if after three times we keep failing we

43:59

just can't get a successful result then we're going to just open the circuit

44:04

and then no more requests are going out so we'll just fill fail fast fill right away right so that

44:11

way we avoid overwhelming the other servant and we and we return fast to our clients which in this case is much better than

44:17

just keep them waiting forever and then uh that circuit is going to

44:22

stay open for in this case uh 15 seconds let's actually reduce it a bit 10 seconds

44:28

and then after those 10 seconds it will try again see if it succeeds if it doesn't it just opens again it

44:33

just keeps open and then we enter into that cycle again so let's see how that uh how that works

44:40

so i'm going to again disable the internet run this

44:48

okay so go to postman hit send let's see what happens behind the scenes

44:54

so it is trying try it a couple of times or perhaps

45:01

already three times so give it a moment and then

45:08

yeah if i go back to postman here it is secret is now open and it is not

45:14

allowing any more calls so no such host is known if i try again let's see what happens

45:20

so yeah secret open and then now we're getting fairly fast results here as you can see

45:25

it's not really waiting so the circuit is open it will be open for about 15 seconds it notices that

45:32

it tried again it didn't succeed so it just stays open so now let's fix that enter the internet

45:39

label that and then yeah again it will take a while but

45:45

eventually this circuit is going to yeah there it is so you could close i'm going to try it again and notice that it

45:51

succeeded close circuit and then we're back into good shape so pretty handy

45:56

and pretty common approach when you have to deal with external dependencies in your microservice

46:03

now so this is this is good but is there a way where we can be a bit more proactive with this so we actually need to wait

46:10

for our clients to be hitting these these situations and causing reliability uh to them so can we

46:17

actually detect this situation before it happens so it turns to be that yeah there's a way and there's this thing

46:23

for this is this thing that we call health checks so health check is a way for your app to have an

46:30

endpoint where anybody else from the outside can query for the health of the service and typically this would be your

46:36

orchestrator system right let's say cornelius that system will be pinging this health endpoint and to check

46:42

how we're doing let's see how we can enable a health check for this app here

46:48

going back to configure services it is as simple as doing this

46:57

adult checks so that registers the health checks uh types into

47:04

our app and now we have to we also have to update our middlewares here we have to induce endpoints we have to

47:13

map health checks right so this is this adds the routes for checking health so let's do

47:22

you can name this anyway i'm just choosing health it's a pretty common name some people would do health c or you

47:29

could do hc whichever works best for you and that's it really i'll hit f5 again

47:39

so let's go back to postman and now what we want to do is to actually

47:44

i'll just grab the the base host so i'm opening another tab here another

47:49

get request now i'm going to do health hit sent healthy

47:57

so this means okay so service is saying yeah we are all good now what happens if i uh disable the

48:04

internet so disabled let's try again send and interestingly we keep getting

48:11

healthy so this is a good point because even when our service is up and running which is

48:17

great uh the dependencies of the service in this case the external service is is down so this is exactly one of these things

48:23

that we want to detect be a health check right so to do that

48:29

what we're going to do is uh let's go back to the project and stop this and what we can do is create what we

48:36

call an a health check uh it's just a class that implements i health check where we can do these

48:42

additional checks so let's add that so let's call it external and point

48:50

check all right so i'm going to grab that name and then it's our namespace

48:58

a hello.net 5. and then let's do a class let's make it

49:05

public yeah the external endpoint health check this class has to implement

49:12

i held check type and

49:20

uh as per doing that it has let's let's actually implement the interface right there

49:27

and what we're going to need since what we need to do is verify i mean the way that we can verify this

49:32

is just by doing a very simple ping right into that open open weather

49:38

endpoint so for that we're going to need that those uh service settings again so we're going to

49:44

need to inject those into our constructor so let's add a constructor for this class actually and just like we did before we use the

49:51

eye options pattern to receive those options and to inject it into this this class

49:58

and we are going to add a property here too we can actually

50:04

just generate that so let me do this uh we'll say green and sign field

50:09

options we don't actually want the options we just want the service settings so let's

50:15

let's do that settings so this dot settings equals options like

50:23

that there it okay and now we have to implement a check helsing

50:29

he'll check held async and so yeah for that again i'm just

50:35

going to grab a little bit of implementation from here

50:41

and let's see what this means so i do have to import a few types so basically

50:46

pink is available in system net network information and

50:52

here i wanted to show you one also one new thing.net five which is uh this way of declaring a new type

50:58

so usually uh before that five you'll have to do well ping ping equals new pink but since

51:05

this is a bit redundant uh because yeah i mean what would i be creating if it's not an instance of pink

51:11

you can just avoid that stuff and you can say equals new and that's all it is you get a new type

51:18

so just a bit of simplification so i appreciate it from the n5

51:23

now next thing let's let me add yeah so this method should be async

51:29

otherwise how are we going to do an async call and what we're doing here is very simple so as you can tell sent being async

51:35

and then we are taking advantage of the open weather host that's available in settings we ping that we get a reply it reply is

51:41

not successful we say hey this is unhealthy otherwise it is a healthy result

51:46

and then we're going to return a healthy resolver there yep so that's our

51:53

external endpoint health check and what we have to do now is to actually register

52:00

that health check with our app so to do that we're going to expand this add health

52:06

checks with sorry with

52:12

a check and in that check we're going to add external and point health check the

52:17

classes we just created we need to give it a name so we'll name it just as

52:22

like the right name will probably be open weather you can use any name here and you can

52:29

you can imagine that as you introduce more dependencies you will just keep adding checks here right so for

52:34

your database for your service broker uh for um i don't know any other

52:41

service that you may need to query outside of your own right in our case it's just open waiter for now it's good enough

52:48

and just by doing that we have health checks let's see f5 again

52:57

so back to postman and i think we don't have network right now yeah we don't have it so let's check health sent

53:04

and boom unhealthy because a health check is telling us now

53:10

if we re-enable internet again

53:16

we should get hopefully healthy health it is yep so like i said

53:24

so this endpoint will become key to whichever monitor or orchestrator system

53:29

is trying to make sure that your service is up and running so that we can detect that situation

53:34

fire some alert and do something about it before our customers start hitting our microservice and hitting this this problem

53:41

now one last thing that i wanted to show you that's uh fairly kind of useful in terms of microservices

53:48

and that's enabled by dotnet five is uh the way that we present logging

53:54

right so let's see so usually let me at least stop and

53:59

start this again uh normally the way that you you see the locks are like this

54:05

right so this is kind of structured logging that's what we can start glowing so each of these lines

54:10

is kind of an object that represents the the level of the log who is emitting that that lock and then

54:16

what the actual log is right so that's that's what it shows there but in a micro service architecture is is

54:23

not very uncommon to want to i mean the recommendation is that

54:28

you just log everything into your console that a typical approach is logged into

54:33

the console and there will be some infrastructure pieces in your deployed environment

54:39

uh that are going to take logs from that a console output and they're going to be probably

54:46

transformed and then eventually sent to some login backend right so there's a

54:51

bit of decoupling between you producing the locks and those locks being collected in some other bag right it's very

54:58

different than than like more of a uh legacy or monolithic systems where you will just

55:03

log to some file or to some location it's really not like that you just log to the output and then

55:08

somehow that output is being transformed into logs eventually however to make that happen uh this kind of

55:15

structured login that we're doing that we're seeing here is not really useful right for for machine it's not machine readable really

55:21

it's human friendly but not machine readable so what we really want to have here is json json output

55:27

how can we get json output here so it's actually very very straightforward with a new edition of net five

55:34

and what we're going to do is just close this and go back to program cs and here we're going to expand uh

55:41

the the way that we configure the host so we're going to say hey let's also configure login

55:48

as we configure login we're going to receive a couple of parameters the context sorry context and

55:56

logging and we're going to get a lambda expression here

56:04

where we can do stuff right so here we're going to we one thing we

56:10

can do is just say hey so we're going to do login.json console the json console

56:17

is a new console available uh alongside all the other login providers uh in in.net available

56:25

now in dotnet5 so just by doing this and we hit f5 you'll see that the logs will now also

56:33

show up as json so let's see so this is the structure login version i mean the the simple

56:41

console version of logs and here is the json version of the same log as you can

56:47

see which will be machine readable by by the login infrastructure in a microservice

56:53

architecture and so yeah that's kind of what we want however now it's it has become actually

56:58

a bit super noisy for us so we can't really tell much of what's going on here so one thing that i like to do is to

57:06

just have a bit of a variation here so depending on the on the development depending on the environment

57:11

either use the simple login or use the json log for this so one thing that you can do is

57:17

since we have uh the hosting environment cycle available in this context object here

57:23

what you can do is something like this let me add to this do a little bit of copy pasting again here

57:28

there so here we're saying hey so only if the hosting environment is

57:34

production go ahead and remove the simple console and then add the json console and that's and that's

57:41

it so now if we run again we're going we'll just back into the simple console

57:46

because we are in development environment but if we were in production this would have turned into

57:52

json so i hope this was useful and if you have any questions or if there's

57:58

something else that you'd like to see in this channel please leave me a note below uh consider

58:04

hitting the like button if you're getting any value out of this and don't forget to subscribe if you'd like to know

58:10

right away when i publish any new videos thanks for watching and see you next time

No comments:

Post a Comment