Skip to content

WIP: ✨ Add probes endpoints - #2888

Closed
Kludex wants to merge 1 commit into
fastapi:masterfrom
Kludex:feat/probes-endpoints
Closed

Kludex wants to merge 1 commit into
fastapi:masterfrom
Kludex:feat/probes-endpoints

Conversation

@Kludex

@Kludex Kludex commented Mar 2, 2021 •

Copy link
Copy Markdown
Contributor

Summary

More like a prototype of /liveness and /readiness endpoints supported natively.

Proposed Solution 😎

This solution proposes storing the probes_state. In that state, we define two attributes: alive and ready. Based on those two attributes, we're able to change the response of the liveness and readiness probes.

Those two attributes can be changed at any moment using the request.app.probes_state.<alive|ready> for now. This is obviously a solution that @tiangolo will not accept, neither I think is a good one. 😅 I think we should have a duck typed solution here. That being said, some ideas:

  • Global variable imported instead of storing the state inside the FastAPI class (which doesn't look that good and it will be exceptional way to do something in FastAPI), for instance:
from fastapi import probes_state
  • Provide a new object the same way BackgroundTasks and Request is inserted, for instance:
from fastapi import FastAPI, LivenessState, ReadinessState

app = FastAPI()

@app.get("/")
async def potato(liveness_state: LivenessState, readiness_state: ReadinessState):
    liveness_state.broken() # Turn alive to False
    liveness_state.correct() # Turn alive to True
    readiness_state.accepting_traffic() # Turn ready to True
    readiness_state.refusing_traffic() # Turn ready to False  

Pros ✔️

  • Looks like people want this feature (check related issue thumbs up).

Cons ❌

  • Easy to implement i.e. doesn't need to be on FastAPI natively.

Related issues 🤓

References

Personal note for curious readers

Let your like here if you want this feature, but don't assume this will be merged, please.

@codecov

codecov Bot commented Mar 2, 2021 •

Copy link
Copy Markdown

Codecov Report

Merging #2888 (339c1be) into master (4d208b2) will decrease coverage by 0.20%.
The diff coverage is 55.00%.

Impacted file tree graph

@@             Coverage Diff             @@
##            master    #2888      +/-   ##
===========================================
- Coverage   100.00%   99.79%   -0.21%     
===========================================
  Files          243      244       +1     
  Lines         7419     7439      +20     
===========================================
+ Hits          7419     7424       +5     
- Misses           0       15      +15     
Impacted Files Coverage Δ
fastapi/applications.py 94.32% <46.66%> (-5.68%) ⬇️
tests/test_probes.py 80.00% <80.00%> (ø)
fastapi/concurrency.py 78.57% <0.00%> (-21.43%) ⬇️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update c09e950...339c1be. Read the comment docs.

@github-actions

github-actions Bot commented Mar 2, 2021

Copy link
Copy Markdown
Contributor

@Kludex Kludex changed the title ✨ Add probes endpoints WIP: ✨ Add probes endpoints Mar 2, 2021
@Mause

Mause commented Mar 3, 2021

Copy link
Copy Markdown
Contributor

I don't see why this is something that needs to be built into fastapi itself, instead of an externally available package?

@Divyadarshee

Copy link
Copy Markdown

@Mause one reason being even external libraries like fastapi-health or fastapi-healthcheck are not working as any other fastapi module when integrated like they are missing out some advantages or features which fastapi has

@Kludex

Kludex commented Mar 3, 2021

Copy link
Copy Markdown
Contributor Author

@Mause You're right. It's even mentioned in the "Cons" section.

But I'm not sure when we cross the line between "should be on FastAPI or not". A clear example is the swagger generation, or even better, the redoc. Why having redoc if we already have the swagger?

I think we should take in consideration for what FastAPI is being used.

@Kludex

Kludex commented Mar 3, 2021

Copy link
Copy Markdown
Contributor Author

@Divyadarshee That's a completely different issue 😅

If a good package that does that doesn't exist already, maybe the community don't need it that much. 😗

But if you want something better than what is around, you should at least open an issue on those packages. It has far higher probability of being attended there than here. 🧐

@Divyadarshee

Copy link
Copy Markdown

Yes @Kludex I agree with that thought process my naïve thought was it would have been a good to have feature but yeah your point is better👍

@ArcLightSlavik

Copy link
Copy Markdown
Contributor

What are the benefits of this solution over doing:

@api.get('/notify/v1/health') 
def get_health():
    return dict(msg='OK')
        readinessProbe:
          httpGet:
            path: /notify/v1/health
            port: 80
        livenessProbe:
          httpGet:
            path: /notify/v1/health
            port: 80

@ycd

ycd commented Mar 5, 2021

Copy link
Copy Markdown
Contributor

What are the benefits of this solution over doing:

@api.get('/notify/v1/health') 
def get_health():
    return dict(msg='OK')
        readinessProbe:
          httpGet:
            path: /notify/v1/health
            port: 80
        livenessProbe:
          httpGet:
            path: /notify/v1/health
            port: 80

Being feature rich, consistency etc. When writing manifest you can use the same path for all your applications without even checking the code because you know it's there, just like /docs and /redoc.

Strong 👍 for this PR.

@ycd

ycd commented Mar 5, 2021

Copy link
Copy Markdown
Contributor

As addition to comment above, FastAPI's main feature is being modern, i can't see anything modern than built-in probes.

Comment thread fastapi/applications.py

self.liveness_probe_url = liveness_probe_url
self.readiness_probe_url = readiness_probe_url
self.probes_state: State = State({"alive": True, "ready": True})

@klaa97 klaa97 Mar 6, 2021 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the reason behind using the State object from Starlette and not a Pydantic dataclass, or anything that constrains the fields of this object to alive and ready, with a bool type?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't have a good answer. I think the moment I choose to do that I was thinking about "more customizable attributes" (some changes are needed for this to be true).

About the dataclass, I'm not sure because we'll need to install the dataclasses backport package for 3.6. It's not really a problem by itself, is just that it will be the first here. 😅

But anyway, your comment is relevant. Thank you :)

I'll apply modifications on the PR once I have more feedbacks about the whole idea. Because as stated in the description, it's kind of a prototype.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@klaa97 I don't see a problem here. If you check on fastapi's code you will not see any dataclasses declared. So I would say LGTM.

@dimaqq

dimaqq commented Jul 26, 2021

Copy link
Copy Markdown
Contributor

It only took 1 g search to discover that these endpoints are used in kubernetes...
May I propose adding a k8: to the PR title?

My 2c: I wish there was a more elegant way to extend or mix in additional functionality (such as 2x docs) into FastAPI than the current keyword arguments.

Comment thread fastapi/applications.py

self.liveness_probe_url = liveness_probe_url
self.readiness_probe_url = readiness_probe_url
self.probes_state: State = State({"alive": True, "ready": True})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@klaa97 I don't see a problem here. If you check on fastapi's code you will not see any dataclasses declared. So I would say LGTM.

Comment thread tests/test_probes.py
@@ -0,0 +1,8 @@
from fastapi import FastAPI, Request

app = FastAPI(liveness_probe_url="/health/liveness")

@staticdev staticdev Nov 2, 2021 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Kludex You probably need to add a test for readiness, since this PR is making code coverage drop from 100%.

@Kludex Kludex changed the title WIP: ✨ Add probes endpoints WIP: ✨ Add k8s probes endpoints Dec 8, 2021
@Kludex Kludex changed the title WIP: ✨ Add k8s probes endpoints WIP: ✨ Add probes endpoints Dec 8, 2021
@Kludex

Kludex commented Dec 8, 2021

Copy link
Copy Markdown
Contributor Author

Comment thread fastapi/applications.py
return JSONResponse({"status": "DOWN"}, status_code=503)
return JSONResponse({"status": "OK"})

self.add_route(self.liveness_probe_url, liveness, include_in_schema=False)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd say it could make sense to let the user decide whether to include these routes in the openAPI or not, WDYT ?

As an use case in favour of having it in the openapi: In my organisation, I need to specify the observability/monitoring capabilities of the services we deploy in a documentation. Having them in the openAPI would make my life easier I think. But I also can imagine scenarii where we don't want / need to have these routes documented.

@Kludex

Kludex commented May 6, 2022

Copy link
Copy Markdown
Contributor Author

This PR has a lot of 👍 , but I don't think it will land. I wouldn't accept it.

@staticdev

staticdev commented May 7, 2022 •

Copy link
Copy Markdown

This PR has a lot of 👍 , but I don't think it will land. I wouldn't accept it.

@Kludex I don't see why, only if you don't want this anymore. If you want, first thing make it pass the CI checks.. it is a good step in making things approved from my experience.

@Kludex

Kludex commented May 7, 2022

Copy link
Copy Markdown
Contributor Author

@Kludex I don't see why, only if you don't want this anymore. If you want, first thing make it pass the CI checks.. it is a good step in making things approved from my experience.

... ???

In any case, I'm not going to rebase, add tests, or whatever here without @tiangolo's feedback.

Comment thread fastapi/applications.py

if self.readiness_probe_url:

async def readiness(req: Request) -> JSONResponse:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As an example, I have the following case:
the readiness of the endpoint is polled constantly, not only until the service is ready to receive traffic.

So this handler contains logic to check the readiness of the module to receive traffic.
Probably it goes against the rules, but this is a life case and ops engineers say that this is a frequent case.
Perhaps it is worth giving the opportunity to redefine the readiness method.

What do u think?

@Siyet

Siyet commented May 16, 2022

Copy link
Copy Markdown

@tiangolo

Copy link
Copy Markdown
Member

Thanks for the proposal @Kludex! 🤓

And thanks for the discussion everyone! ☕

Here's my rationale (more or less) to decide these things:

I consider two options:

  • Teaching people how to build something directly, explaining the needed concepts, code, and teaching them how to do it themselves.
  • Include some of that functionality in the library (in this one or an additional library, etc), teaching them the needed concepts, and how to use this new feature/library (instead of teaching them how to do things directly themselves).

If the effort required from users to learn the new functionality in the library is a lot less than what wold be needed to learn how to build it themselves, I would put it in the library, if not, I would rather teach them the underlying concepts and code.

At some point, they might still need to learn the underlying concepts and code anyway, and if they had to learn an abstraction before learning the actual concepts, in the end, they had to learn the double.

Also, if the new feature/library adds some noticeable improvement in some way, e.g. developer experience (autocompletion, type annotations) compared to doing things by hand, or makes things particularly easier, then I add the feature/library.

The other thing is, if I document how to add probes by hand, people that come searching for that can find it. But if it's part of the library as a feature, and more keyword arguments, everyone will end up seeing them, and maybe wondering what that's for, and having to learn it or feel they don't know a part of the tool.

I probably consider other things that I don't remember right now from the top of my head, but you get the point.


In this particular case, I don't think having this as part of the library is saving users that much effort compared to teaching them how to write the code themselves. And also "liveness" and "readiness" will be quite dependent on the application. So, adding all the needed parameters and configs would require quite some complexity on the library and complexity people would have to learn. So I would prefer to teach them how to add the endpoints themselves and what things to consider.

So, I'll pass on this PR. But I would take a PR adding docs about creating probes by hand. 🤓 ☕

@tiangolo tiangolo closed this Nov 14, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.