Skip to content

multiprocess in uwsgi leads generate_latest to sometimes contain duplicates #647

Closed

Description

@tommyjcarpenter

Question: can the generate_latest method detect and fix duplicates?

The code for my app is pretty simple. At the top of middleware.py I do:

# Metrics
# See https://github.com/amitsaha/python-prometheus-demo/blob/master/flask_app_prometheus_multiprocessing/src/helpers/middleware.py
registry = CollectorRegistry()
multiprocess.MultiProcessCollector(registry)
REQUEST_COUNT = Counter(
    "indexapi_request_count",
    "help: App Request Count",
    ["method", "endpoint"],
    registry=registry,
)


def setup_metrics(app):
    # https://github.com/prometheus/client_python

    @app.route("/metrics")
    def metrics():
        data = generate_latest(registry)
        print(data)
        return Response(data, mimetype=CONTENT_TYPE_LATEST)

somewhere in middleware.py during _call I do:

REQUEST_COUNT.labels(request.method, path).inc()

in dockerfile I have:

RUN mkdir /tmp/prom_data
ENV prometheus_multiproc_dir /tmp/prom_data

In my main app.py I have:

app = Flask(__name__)
app.wsgi_app = middleware.Middleware(app.wsgi_app)
CORS(app)

logger.debug("Starting metrics")
middleware.setup_metrics(app)

I run UWSGI with:

CMD uwsgi --http 0.0.0.0:8080 --wsgi-file indexapi/app.py --callable app --buffer-size 30000  --processes 4 --threads 4

It seems to work fine, as in no matter what thread processes the request, the metric gets updated once. However, sometimes the text contains duplicate output:

 ~/D/python-indexapi   prom    curl localhost:4444/metrics                                                                            Mon May  3 12:36:28 2021
# HELP indexapi_request_count_total Multiprocess metric
# TYPE indexapi_request_count_total counter
indexapi_request_count_total{endpoint="/index",method="GET"} 1.0
# HELP indexapi_request_count_total help: App Request Count
# TYPE indexapi_request_count_total counter

 ~/D/python-indexapi   prom    curl localhost:4444/metrics                                                                            Mon May  3 12:36:29 2021
# HELP indexapi_request_count_total Multiprocess metric
# TYPE indexapi_request_count_total counter
indexapi_request_count_total{endpoint="/index",method="GET"} 1.0
# HELP indexapi_request_count_total help: App Request Count
# TYPE indexapi_request_count_total counter
indexapi_request_count_total{endpoint="/index",method="GET"} 1.0
# HELP indexapi_request_count_created help: App Request Count
# TYPE indexapi_request_count_created gauge
indexapi_request_count_created{endpoint="/index",method="GET"} 1.6200591934205577e+09

 ~/D/python-indexapi   prom    curl localhost:4444/metrics                                                                            Mon May  3 12:36:29 2021
# HELP indexapi_request_count_total Multiprocess metric
# TYPE indexapi_request_count_total counter
indexapi_request_count_total{endpoint="/index",method="GET"} 1.0
# HELP indexapi_request_count_total help: App Request Count
# TYPE indexapi_request_count_total counter

This is very perplexing to me. We can see

# TYPE indexapi_request_count_total counter
indexapi_request_count_total{endpoint="/index",method="GET"} 1.0
# HELP indexapi_request_count_total help: App Request Count

# TYPE indexapi_request_count_total counter
indexapi_request_count_total{endpoint="/index",method="GET"} 1.0
# HELP indexapi_request_count_created help: App Request Count

Also, when the duplicate is detected, this gauge appears out of nowwhere.

Activity

  1. csmarchbanks commented on May 3, 2021

    @csmarchbanks
    Member

    Hello,

    For now you can workaround this issue by removing registry=registry when you create REQUEST_COUNT. In fact, you may want to move the lines:

    registry = CollectorRegistry()
    multiprocess.MultiProcessCollector(registry)
    

    to inside of your metrics route handler. When running in multi process mode all metrics are always registered so it is unnecessary to specify a registry when creating a metric, and can lead to the doubling of metrics that you see (one for multi-process and one for the local process).

    At a minimum I think we need to document the registry behavior with multi process. We might also be able to error or warn in the case of duplicate metrics being registered for multi-process, but I would have to think some if that is breaking any legitimate use cases.

  2. tommyjcarpenter commented on May 3, 2021

    @tommyjcarpenter
    Author

    @csmarchbanks please bare with me here I'll try to explain what happened when I did this:

    So, removing those lines, and the registry from the counter, but leaving in the following in our Dockerfile:

    RUN mkdir /tmp/prom_data
    ENV prometheus_multiproc_dir /tmp/prom_data
    

    (is that all that is needed to trigger "multiprocess mode" after I removed those lines???)
    Leads to the scenario where some calls to /metrics return the metric, and some do not at all. Moreover, only some calls that increment the counter Actually increment it, and some do not, leading to incorrect behavior.

    Please let me know if I missed a step. Basically the only thing I'm doing to trigger "multiprocess" is that Dockerfile addition and thats it, all the counters are registry agnostic and the registry code lines you mentioned are gone.

    However, keeping all that, but also following "Option 1" here seems to be working for us:
    https://echorand.me/posts/python-prometheus-monitoring-options/

    What happens now is that, every 15 seconds, when metrics are pulled, depending on which worker is responding, it responds with the "right" metric for that worker". Like sometimes I will get:

    indexapi_request_count_total{bearer_passed="false",endpoint="/index",method="GET",worker_id="2"} 2.0
    # HELP indexapi_request_count_created help: App Request Count
    # TYPE indexapi_request_count_created gauge
    

    and others I will get:

    # TYPE indexapi_request_count_total counter
    indexapi_request_count_total{bearer_passed="false",endpoint="/index",method="GET",worker_id="1"} 1.0
    # HELP indexapi_request_count_created help: App Request Count
    # TYPE indexapi_request_count_created gauge
    

    But this creates an explosion of metrics that is undesired that we have to sum over (like 4 workers etc). but it works for now.

    I should note that we are using UWSGI and not gunicorn, but the docs on multiprocess mode either explictly assume gunicorn, or do not discuss anything other than that. Is this even possible with UWSGI?

  3. tommyjcarpenter commented on May 3, 2021

    @tommyjcarpenter
    Author

    in fact, this leads to the same behavior as if I just remove the dockerfile stuff at all; so actually I dont have any idea how to "trigger" multiprocessing mode, after I remove the code you mentioned; can you please let me know how?

  4. csmarchbanks commented on May 4, 2021

    @csmarchbanks
    Member

    You will still need the CollectorRegistry and MultiProcessCollector lines, they could just be moved into the scope of just the handler for /metrics. That way metrics are less likely to try to use a registry since it would be out of scope.

    The minimal change to your example is removing registry=registry. If that is not working I will take a further look tomorrow. Sorry if my first message wasn’t clear!

  5. tommyjcarpenter commented on May 4, 2021

    @tommyjcarpenter
    Author

    Your latest suggestion seems to have fixed the issue (after writing the redis reimplementation!). Thanks a lot. I defintiely think maybe some documentation could help:

    1. be careful not to use registry= in counters (why is that there?)
    2. put the registry definition in the handler and not at the module level
    3. maybe some instructions for UWSGI? For example, theres a gunicorn instruction for child exits; but not sure of the UWSGI equivelent.
  6. csmarchbanks commented on May 11, 2021

    @csmarchbanks
    Member

    @tommyjcarpenter I created #651 to try to avoid duplicate issues in the future, would you be willing to take a look please?

  7. tommyjcarpenter commented on May 12, 2021

    @tommyjcarpenter
    Author

    @csmarchbanks thank you, I left a few comments

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions