strawberry: Support for query complexity
Hey folks, I while ago I wrote down some ideas on how we can add support for query complexity. For this we’ll need two things:
- An extensions that calculates the costs based on an operation
- Support for customising the costs based on fields/arguments
For customising costs on fields and arguments I was thinking about something like this:
import strawberry
@strawberry.type
class Query:
@strawberry.field(cost=2)
def expensive_list(self, limit: Annotated[int, strawberry.argument(cost_multiplier=1)]) -> list[str]:
return ["Item"] * limit
Here we are saying that each individual item in the expensive_list field costs 2, and the total is a multiplication between the field cost and the limit, so the result would be:
field_cost × limit × 1
We can also have defaults like this:
class StrawberryConfig:
# Existing attributes and methods ...
default_argument_cost_multiplier: Dict[str, Union[int, float]] = {
"limit": 1,
"first": 1, # probably not needed, but worth showing as an example
"last": 1
}
default_argument_cost_multiplier is a map between argument name and their multiplier, though I don’t like the name that much.
What do you think?
About this issue
- Original URL
- State: open
- Created 3 years ago
- Comments: 19 (16 by maintainers)
@patrick91
I’ve been looking at this quite a bit as well.
Here are some resources I’ve found and things I like about them that we could maybe take advantage of
I do like the
Annotatedwithfield/argumentidea, because it makes it very clear what the cost is. A potential tradeoff is that the cost of fields is scattered around the codebase, rather than being defined explicitly in one place, like the map idea.I think being able to define your own Estimators and pass those into the Extension could be a great way to provide defaults and to give a lot of flexibility for clients to do things themselves
So my overall thoughts on what I’d like to be able to do/have:
Something like
QueryComplexityLimiterextension@serramatutu the rust parser is almost ready for beta use 😉 Even then though, we should support pure-python for now.
+1 on separating cost calculation logic vs limitation logic, this would enable easy abstraction of both components