I am trying to write my own proxy extensions. Both, burp suite as well as mitmproxy allows us to write extensions. 
Till now, I am successful with intercepting the request and response headers, and write it to my own output file.
The problem is, I get frequent requests and responses at anonymous time and at the same time, the output is getting written in the file. 
How should I identify that which response belongs to which particular request ?? 
If we see in burp suite, when we click on particulat URL in target, we see two different tabs- "Request" and "Response". How is burp suite identifying this ? 
Similar is the case with mitmproxy. 
I am new to proxy extensions, so any help would be great. 
----EDIT----
If any additional information is required then pls let me know.
In mitmproxy 0.10, a flow object is passed to the response handler function. You can access both flow.request and flow.response.
how to identify http response belongs to which particular request through python?