Showing posts with label mysql. Show all posts
Showing posts with label mysql. Show all posts

Thursday, August 09, 2007

PHP Unable to Connection to MySQL

Over the past few weeks we've run into an issue on flora where people attempting to any database-driven content are greeted with a MySQL connection error. The connection problem is intermittent and seems to run its course after a few hours. During that time I've been asking people to click the reload button in their browser; this usually results in them getting to where they were headed. Luckily, we're not hosting any content for the general public or I wouldn't be able to rely on this solution.

The first time it happened I couldn't find anything in the logs that led me to a solution. Since the problem eventually went away, and because I had no way of really seeing what was going on at the time I let it slide. However, about a week later another bout of connections errors started occurring. We'll be moving some high-use, general-public content onto the server in the near future and so now a solution needs to be found.

So far I've been unable to trace the source of the connection errors. There's nothing indicating a problem with Apache or MySQL (such as MySQL crashing). We are logging PHP errors and here's the relevant error message:
PHP Warning: mysql_connect() [function.mysql-connect]: Lost connection to MySQL server during query in %DBC% on line 8
%DBC% would be the connection script and for this particular file line 8 is the mysql_connect() statement. Nothing too helpful here except to note that we're not even making the connection.

One of the users had provided a printout of the error received on the front end. I don't recall there being anything helpful, but I tossed the print0ut after the problem righted itself. A mistake since the printout included output from mysql_error(). Though I can't say for certain what kind of error was being reported I don't believe I would have tossed the printout if it was truly useful. At any rate, I modified the connection script so that mysql_error() is recorded in the PHP error log. This won't help currently, but if/when connection errors are encountered in the future I'll have a little more information to help with debugging.

After the initial occurrence I spent some time looking for information on the web, but nothing I found showed any promise. Most of the references I found regarded too many connections or too much data or similar issues. Those just doesn't seem to be the case here; I don't recall any of those being part of the error reported.

After the second occurrence I did some more searching and believe I am closer to a solution. If my recollection is correct about the nature of the error reported by mysql_error() then I suspect we may just be running into a connection timeout. The server has been running fairly sluggishly of late and it does seem possible that PHP may be unable to connect by the timeout limit.

MySQL is set to time out after 5 seconds. But in reviewing the logs and status information I don't believe this is the source of the problem. MySQL should be reporting any connection timeout on its end as aborted, but the number of aborted connection reported by MySQL (10) is significantly smaller than the number of connection errors reported by PHP (~200). With this in mind, the most likely timeout is occurring on the client. What this means is that MySQL is not responding at all by the timeout set by PHP, 60 seconds.

The solution would be to increase the timeout on the client, server, or both. However, I don't want to make this change prematurely. I'm thinking of waiting until the problem emerges again in order to see what kind of errors are thrown by mysql_error().

If I am unable to find a solution the next step might be to try posting a query on the MySQL Community and MySQL Performance Blog forums.

References:
Alternative sources
I do have some thoughts on other issues causing the connection problems. These, however, seem less likely. I am listing them here mainly as a reminder to myself in case the connection timeout doesn't pan out.

Perhaps PHP isn't freeing connections and is running out of usable connections. The server is currently set to 100 connections by default and we don't get nearly enough traffic to approach this limit. Plus, if PHP acts appropriately it should be disconnecting the connection once it has completed processing a page. However, it is conceivable that something is going on that is preventing this from happening. If PHP isn't disconnecting when finished with a page the connections could inch up towards the limit.
Another possibility, maybe MySQL is running out of back_log connections. The back_log connections are those that have been connected to MySQL but have yet to be handed off to a child process. This is currently set at 50, which should be more than enough to handle our traffic load.

Friday, July 13, 2007

Optimizing MySQL

Slow on the draw
Some of our users were complaining of slow performance on one of our web-based utilities. There are, unfortunately, a number of factors that can affect system performance. I haven't spent much time learning the best practices for profiling a system to discover the source of bottlenecks, but my hunch was that the problem was in MySQL.

The users in question were having problems with slow INSERT/UPDATE statements. I used the status and variables tabs of PHPMyAdmin (PMA) to try and find any possible bottlenecks in MySQL. These tabs are equivalent to the SHOW STATUS and SHOW VARIABLES SQL statements respectively. The nice thing about PMA is that it will highlight any values it thinks may be causing a problem.

At first I thought locking might be the source of the slowdown, but after some testing I don't think that's the case. In my informal click test (clicking the save button on the form being used over and over) the worst delay I ran into was about five seconds. The delay time being experienced by the users was in the neighborhood of thirty seconds.

When I thought about the delay more I remembered a similar problem I've experienced myself when logging in to one of the utilities. The log in could easily take up to 30 seconds at times. It took a while to nail down the possible culprit, but I believe it may be the MySQL table cache. These are the tables MySQL has accessed that it stores in memory in order to speed up future access. After a bit more testing I've come to the conclusion that a significant slow-down may be occurring while as MySQL removes one table from the cache and loads another one. By upping the value of the table_cache parameter in my.cnf I believe that the delay caused by this operation should be avoided.

I upped the table_cache from 64 to 80. I thought about doubling the value to have a bit of a safety net, but the drawback would be higher RAM usage. I'll have to watch the opened_tables status variable and see if the new cache value is sufficient.

I won't be able to see the affects until next week. The users say the problem seems to be worse in the mornings. This is likely the most probable time that the table cache is being optimized based on usage, with tables going in and out of the cache.

Staying off the disk
Table locking isn't totally out of the question, though. With up to five people entering data at the same time it's possible that a user could get stuck at the end of a locking queue waiting for the others to finish. There's not a lot that can be done to prevent lock conflicts. We can raise the priority of SELECTs or decrease the priority of INSERTs/UPDATEs. Otherwise switching to InnoDB might show something of a performance increase (from the user's perspective). Since InnoDB uses row-level locking the overall time a user spends waiting on locks could decrease significantly. Of course, InnoDB isn't without its drawbacks in the form of higher overhead and the inability to perform full text searches. (Full text search is not a concern for the table involved in this instance.)

While I was modifying the operational parameters of MySQL I went ahead and updated the tmp_table_size option as well. The number of temporary tables being written to disk was relatively high when compared to the total number of temporary tables created (almost 50%). This can cause sluggish response time as well so I'm hoping that updating this value (32M to 48M) will also show an improvement in server responsiveness. I have a feeling I'll need to push this even higher, but again I need to keep an eye on overall RAM usage. All this optimization will prove pointless if the system has to start paging out to disk because the RAM is full.

Keeping it real (fast)
One issue to keep in mind with regard to server performance is indexes. A join should always be done on an indexed field, otherwise there can be serious lag as the system seeks out matching records. We appear to have a large number of join operations running that do not use indexes. Finding the offending SQL statements will require a bit of investigation, however, and so I don't expect to address quickly. Also, I don't believe this is an issue in the user-experienced sluggishness so I'll probably address these as I come across them.

References

Wednesday, March 21, 2007

MySQL Stored Procedure Crashing Server?

I'm in the process of converting the IERI student assessment data into a relational format. Currently the data is spread betwee nsixteen different tables (one for each year/subject combination). The method I was attempting to use to transform the data was as follows:
  1. Create a temporary table for each form of each test (Algebra Form A, Algebra Form B, etc.) containing a single row for each student/answer combination.
  2. Use a stored procedure to take the data from the temporary table and insert it into the tables the will contain the final data.
Creating the temporary table is tedious in that a self-join has to be done on the original table for each answer. However, this is well worth it as the data is pretty much in a usable format for insertion into the final tables.

Unfortunately, I ran into a major problem when attempting to get the stored procedure to work. The basic and programmatic flow I designed for the procedure seems to be fine. I was able to test with some dummy data and had no problems. When I added the SQL code to do the necessary selects I encountered a serious error … the MySQL daemon appeared to crash. The server is quick to restart after a crash so it's hard to say without doing some investigation, but it does appear to be a crash.

At first I thought maybe I was having a memory limit problem since the amount of data (10700 rows) is fairly large compared to what we normally work with. (Our server isn't top-notch either.) However, after watching resource utilization (using top) I was unable to see any significant usage during temporary table creation or stored procedure operation. Actually, the server seemed to crash immediately after the stored procedure was called.

The stored procedure consisted of a few variables, a few SQL statement executions (one to populate variables, another to insert data into tables), and a cursor for accessing data from the temporary table. Overall, the structure of the stored procedure seems to be fine and is in line with many samples I've seen on dev.mysql.com. The single-use SQL statements are run using PREPARE and EXECUTE since they utilize variables that are populated by the cursor.

Through much trial and error I was able to determine that the single-use SELECT statement I was using to populate a variable is the source of the crash. Upon execution of that statement the server crashes. The specific problem seems to be when I access a table, as I can use a more basic SELECT (something like SELECT 10 INTO @recordref) and everything seems fine.

Since I don't see any way to get this working as things now stand I'm going to do everything through SQL queries. In the meantime, though, I decided to try doing the transformation as a couple of queries that use subqueries to set up the relational-friendly data tables. Though this is really a one-use setting, there's some thought out there that currently in MySQL it can be faster to do things in this manner (see Roland Bouman: Refactoring MySQL Cursors).

As a reminder, when using the MySQL Query Browser a script is better for something like this rather than a query. The main difference between the two access methods is that all the queries in a script are run in one connection/session whereas each query is run in its own connection. Using a script will allow the creation of temporary tables which, in this particular instance, should speed things up noticeably. First I'll develop all the code I need as queries then create one large script to process all the data.

Sometime in the next few weeks I think I'll upgrade to a newer version of MySQL and see if that solves the problem. If that doesn't work I'll post a question on the forums and see if anyone has any thoughts. After that I'll think about posting a bug report. I'm a bit leery about doing so after my mozilla bug reporting experience, but as long as I'm thorough I shouldn't be given the smack down.

Friday, October 27, 2006

IN Condition Tricks

Not your type, huh? Change for the better.
I needed to pull some data from our contact database (ichaos) based on ZIP code. The list of codes to use was fairly lengthy and I was concerned about the length of a possible WHERE clause since the data is stored as text to accommodate both the 5-digit and 9-digit US formats (not to mention postal codes from other countries).

Even though the column is stored as text I decided to use the IN() condition to provide the condition. This worked much better than I expected. Not only were the specific matches returned (we used the 5-digit variation in the conditional), but MySQL also returned any variations on the provided condition.

The following SQL statement:
SELECT … WHERE post_code IN (12345);
returns not only the records matching 12345 but also any that match on the first five characters (such as 12345-6789).

The reason this search appears to work appears to do with type conversion (see Type Conversion in Expression Evaluation). Since we are attempting to compare a string to a number the two arguments are converted to floating point numbers by default. To have better control over the comparison we could use the LEFT() function to truncate the zip code to 5 digits, then the CAST() function to control the conversion of the column used in the statement.


Your custom order
While performing my search I noticed another useful tip for the IN() condition in the comments of the SELECT syntax documentation page. If you use an IN() condition in the ORDER BY clause you can specify a custom ordering scheme for a column. So the following statement:
SELECT … ORDER BY %column_name% IN (%value1%, %value2%), %column_name%;
will order the column first by the values specified in the IN() condition followed by the default ordering scheme for the type of data stored in that column.


Update 2006/12/05:
After some further testing I've found that the custom ordering trick doesn't work as I thought. What it does is group the records matching the condition and sort those as a group. It does not sort the values according to the order specified in the parenthesis. If you want specific control of the ordering you'll have to do a separate IN() condition for each value, thus grouping all the records with that value.

What this means is that my previous example will place all records with %value1% and %value2% at the top, but the sorting of those values will be whatever the default is (the order entered in the database unless other sorting options have been specified).

To get the results I had been seeking you have to use something more like the following:
SELECT … ORDER BY %column_name% IN (%value1%), %column_name% IN (%value2%), %column_name%;