0

I implemented an azure function where in every request I read the contents from a local file (about 100 bytes) and I return the response. I read diffrent parts of the file depending on query string (fromPosition).

public class Reader
{
    public static byte[] GetData(int fromPosition)
    {
        using(var fileStream = File.OpenRead("myLocalFilePath"))
        {
            byte[] data = new byte[100];
            fileStream.Position = fromPosition;
            fileStream.Read(data, 0, 100);
            return data;
        }
    }
}

The problem with this code is that it takes about 1 sec to open the file and to return the data in every request.

I modified the code to keep always the file open (removed using statement, the static FileStream is opened once and not disposed), used also lock to protect from multiple requests.

public class Reader
{
    static object locker = new object();
    static FileStream fileStream;
    public static byte[] GetData(int fromPosition)
    {
        lock(locker)
        {
            if(fileStream == null)
                fileStream = File.OpenRead("myLocalFilePath");

            byte[] data = new byte[100];
            fileStream.Position = fromPosition;
            fileStream.Read(data, 0, 100);
            return data;
        }
    }
}

This code takes about 1 sec in the first request, but in all next requests it returns immediately (0 milliseconds). So I have a massive improvement in speed, my azure function now completes quickly, I suppose this is also good for the cost.

Is there any downside of keeping the FileStream handle (just one handle) always open regarding the azure cost?

albert
  • 1,493
  • 1
  • 15
  • 33
  • As far as I know, a single instance of a function cannot be accessed by multiple clients at the same time. If necessary, new instances of the function will be started. Therefore, there is no need to lock access. – Alexander Petrov Feb 27 '21 at 11:17
  • It is OK to use static members in azure functions. – Alexander Petrov Feb 27 '21 at 11:19
  • I think static variables are retained. File stream is not null in my second request. You can test it. It’s not cold start in every request – albert Feb 27 '21 at 11:27
  • If the second request came after the first one ended, it will be served by the same function. But if the second request came while the function is busy processing the first one, then a new instance of the function will be started. This is the essence of automatic scaling. – Alexander Petrov Feb 27 '21 at 11:31
  • Is this Durable function? Sounds very weird that you are reading from "local file" every time as Functions are meant to be stateless. Is it some kinda mounted drive or something? Perhaps there is a cold start associated with mounting of the such drive? – Kashyap Mar 01 '21 at 03:13

1 Answers1

0

I would guess it's the good old cold start problem.

See other (possibly cheaper) ways to deal with it in this answer.

Kashyap
  • 15,354
  • 13
  • 64
  • 103